Элементы <input>
типа date
создают поля ввода и позволяют пользователю ввести дату, либо использовать text box для автоматической проверки контента или использовать специальный интерфейс date picker. Возвращаемое значение включает год, месяц, день, но не время. Используйте поля ввода time (en-US) или datetime-local, чтобы вводить время или дату+время соответственно.
Отображение date
различается в зависимости от браузера, кроме того не все браузеры поддерживают date
. Подробнее см. Browser compatibility. В неподдерживаемых браузерах элемент будет отображаться как обычный <input type="text">
.
Интерактивный пример
Среди браузеров со своим интерфейсом для выбора даты, есть интерфейс браузеров Chrome и Opera, который выглядит так:
В Edge он выглядит так:
А в Firefox выглядит так:
Value | Возвращает DOMString , с датой в формате гггг-мм-дд, **или пустую строку |
---|---|
События | change (en-US) и input (en-US) |
Поддерживаемые атрибуты | autocomplete , list , readonly , and step |
IDL attributes | list , value , valueAsDate , valueAsNumber . |
Методы | select() (en-US), stepDown() (en-US), stepUp() (en-US) |
Значение
Возвращает DOMString
, представляющий значение даты введённой в input. Вы можете установить значение по умолчанию для элемента с помощью добавления атрибута в value
, например:
<input id="date" type="date" value="2017-06-01">
Примечание: Помните, что отображаемый формат даты отличается от настоящего значения value
– отображаемый формат даты будет выбран, базируясь на региональных параметрах браузера пользователя, тогда как значение value
всегда имеет формат гггг-мм-дд
.
Вы также можете получить или установить значение даты в JavaScript с помощью свойств value
и valueAsNumber
элемента input. Например:
var dateControl = document.querySelector('input[type="date"]');
dateControl.value = '2017-06-01';
console.log(dateControl.value); // prints "2017-06-01"
console.log(dateControl.valueAsNumber); // prints 1496275200000, a JavaScript timestamp (ms)
Этот код выбирает первый элемент <input>
, type
которого date
и устанавливает значение даты в 2017-06-01
(1 Июня 2017). Затем он считывает это значение обратно в строковом и числовом форматах.
Дополнительные атрибуты
В дополнение к общим атрибутам для всех элементов <input>
, у "date"
есть следующие дополнительные атрибуты:
Атрибут | Описание |
---|---|
max |
Максимально возможная дата для установки |
min |
Минимально возможная дата для установки |
step |
Шаг (в днях), с которым будет изменяться дата при нажатии кнопок вниз или вверх данного элемента |
max
Максимально возможная дата для установки. Если value
является более поздней датой, чем дата, указанная в атрибуте max
, элемент отобразит ошибку при помощи constraint validation (en-US). Если в атрибуте max
указано значение, не удовлетворяющее формату yyyy-MM-dd
, значит элемент не будет иметь максимальной даты.
В атрибуте max
должна быть указана строка с датой, которая больше или равна дате, указанной в атрибуте min
.
min
Минимально возможная дата для установки. Если value
является более ранней датой, чем дата, указанная в атрибуте min
, элемент отобразит ошибку при помощи constraint validation (en-US). Если в атрибуте min
указано значение, не удовлетворяющее формату yyyy-MM-dd
, значит элемент не будет иметь минимальной даты.
В атрибуте min
должна быть указана строка с датой, которая меньше или равна дате, указанной в атрибуте max
.
step
{{page(«/ru/docs/Web/HTML/Element/input/number», «step-include»)}}
Для полей ввода date
значение step
задаётся в днях; и является количеством миллисекунд, равное 86 400 000 умножить на значение step
(получаемое числовое значение хранится в миллисекундах). Стандартное значение step
равно 1, что означает 1 день.
Примечание: Для полей ввода date
указание для step
значения any
даёт такой же эффект, что и значение 1
.
Использование полей ввода c типом date
На первый взгляд, элемент <input type="date">
выглядит заманчиво — он предоставляет лёгкий графический интерфейс для выбора даты, нормализует формат даты, отправляемой на сервер независимо от локальных настроек пользователя. Тем не менее, есть проблемы с <input type="date">
в связи с ограниченной поддержкой браузеров.
В этом разделе мы посмотрим на простые, а затем и более сложные способы использования <input type="date">
, и позже дадим советы по уменьшению влияния поддержки браузерами (смотрите Handling browser support).
Примечание: Надеемся, со временем поддержка браузерами станет повсеместной, и эта проблема исчезнет.
Как использовать date?
Самый простой способ использовать <input type="date">
— это использовать его с элементами <input>
и label, как показано ниже:
<form>
<div>
<label for="bday">Введите дату вашего рождения:</label>
<input type="date" id="bday" name="bday">
</div>
</form>
Установка максимальной и минимальной даты
Вы можете использовать атрибуты min
и max
, чтобы ограничить дату, которую может выбрать пользователь. В следующем примере мы устанавливаем минимальную дату 2017-04-01
и максимальную дату 2017-04-30
. Пользователь сможет выбрать дату только из этого диапазона:
<form>
<div>
<label for="party">Укажите предпочтительную дату события:</label>
<input type="date" id="party" name="party" min="2017-04-01" max="2017-04-30">
</div>
</form>
В результате выполнения кода, пользователь сможет выбрать любой день апреля 2017 года, но не сможет выбрать и даже просмотреть дни других месяцев и годов, в том числе через виджет date picker.
Примечание: вы должны уметь использовать атрибут step
, чтобы менять количество дней, на которое будет происходить шаг при изменении даты (например, чтобы сделать выбираемыми только субботы). Однако, не похоже, что это где-то применялось на данный момент.
Controlling input size
<input type="date">
doesn’t support form sizing attributes such as size
. You’ll have to resort to CSS for sizing needs.
Validation
By default, <input type="date">
does not apply any validation to entered values. The UI implementations generally don’t let you enter anything that isn’t a date — which is helpful — but you can still leave the field empty or (in browsers where the input falls back to type text
) enter an invalid date (e.g. the 32nd of April).
If you use min
and max
to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you’ll have to check the results to be sure the value is within these dates, since they’re only enforced if the date picker is fully supported on the user’s device.
In addition, you can use the required
attribute to make filling in the date mandatory — again, an error will be displayed if you try to submit an empty date field. This, at least, should work in most browsers.
Let’s look at an example — here we’ve set minimum and maximum dates, and also made the field required:
<form>
<div>
<label for="party">Choose your preferred party date (required, April 1st to 20th):</label>
<input type="date" id="party" name="party" min="2017-04-01" max="2017-04-20" required>
<span class="validity"></span>
</div>
<div>
<input type="submit">
</div>
</form>
If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
Here’s a screenshot for those of you who aren’t using a supporting browser:
Here’s the CSS used in the above example. Here we make use of the :valid
and :invalid
CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a <span>
next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can’t be styled or shown effectively.
div {
margin-bottom: 10px;
display: flex;
align-items: center;
}
label {
display: inline-block;
width: 300px;
}
input:invalid+span:after {
content: '✖';
padding-left: 5px;
}
input:valid+span:after {
content: '✓';
padding-left: 5px;
}
Предупреждение: Important: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).
Handling browser support
As mentioned above, the major problem with using date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:
Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
The second problem is the more serious of the two; as we mentioned earlier, with a date input, the actual value is always normalized to the format yyyy-mm-dd
. With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates, for example:
ddmmyyyy
dd/mm/yyyy
mm/dd/yyyy
dd-mm-yyyy
mm-dd-yyyy
Month dd yyyy
One way around this is to put a pattern
attribute on your date input. Even though the date input doesn’t use it, the text input fallback will. For example, try viewing the following example in a non-supporting browser:
<form>
<div>
<label for="bday">Enter your birthday:</label>
<input type="date" id="bday" name="bday" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}">
<span class="validity"></span>
</div>
<div>
<input type="submit">
</div>
</form>
If you try submitting it, you’ll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn’t match the pattern nnnn-nn-nn
, where n
is a number from 0 to 9. Of course, this doesn’t stop people from entering invalid dates, or incorrectly formatted dates, such as yyyy-dd-mm
(whereas we want yyyy-mm-dd
). So we still have a problem.
div {
margin-bottom: 10px;
}
input:invalid + span {
position: relative;
}
input:invalid + span:after {
content: '✖';
position: absolute;
right: -18px;
}
input:valid + span {
position: relative;
}
input:valid + span:after {
content: '✓';
position: absolute;
right: -18px;
}
The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, and year in separate controls (<select>
elements being popular; see below for an implementation), or to use a JavaScript library such as jQuery date picker.
Examples
In this example we create two sets of UI elements for choosing dates: a native <input type="date">
picker and a set of three <select>
elements for choosing dates in older browsers that don’t support the native input.
HTML
The HTML looks like so:
<form>
<div class="nativeDatePicker">
<label for="bday">Enter your birthday:</label>
<input type="date" id="bday" name="bday">
<span class="validity"></span>
</div>
<p class="fallbackLabel">Enter your birthday:</p>
<div class="fallbackDatePicker">
<span>
<label for="day">Day:</label>
<select id="day" name="day">
</select>
</span>
<span>
<label for="month">Month:</label>
<select id="month" name="month">
<option selected>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
</span>
<span>
<label for="year">Year:</label>
<select id="year" name="year">
</select>
</span>
</div>
</form>
The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)
input:invalid+span:after {
content: '✖';
padding-left: 5px;
}
input:valid+span:after {
content: '✓';
padding-left: 5px;
}
JavaScript
The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="date">
, we create a new <input>
element, set its type
to date
, then immediately check what its type is set to — non-supporting browsers will return text
, because the date
type falls back to type text
. If <input type="date">
is not supported, we hide the native picker and show the fallback picker UI (<select>
) instead.
// define variables
var nativePicker = document.querySelector('.nativeDatePicker');
var fallbackPicker = document.querySelector('.fallbackDatePicker');
var fallbackLabel = document.querySelector('.fallbackLabel');
var yearSelect = document.querySelector('#year');
var monthSelect = document.querySelector('#month');
var daySelect = document.querySelector('#day');
// hide fallback initially
fallbackPicker.style.display = 'none';
fallbackLabel.style.display = 'none';
// test whether a new date input falls back to a text input or not
var test = document.createElement('input');
test.type = 'date';
// if it does, run the code inside the if() {} block
if(test.type === 'text') {
// hide the native picker and show the fallback
nativePicker.style.display = 'none';
fallbackPicker.style.display = 'block';
fallbackLabel.style.display = 'block';
// populate the days and years dynamically
// (the months are always the same, therefore hardcoded)
populateDays(monthSelect.value);
populateYears();
}
function populateDays(month) {
// delete the current set of <option> elements out of the
// day <select>, ready for the next set to be injected
while(daySelect.firstChild){
daySelect.removeChild(daySelect.firstChild);
}
// Create variable to hold new number of days to inject
var dayNum;
// 31 or 30 days?
if(month === 'January' || month === 'March' || month === 'May' || month === 'July' || month === 'August' || month === 'October' || month === 'December') {
dayNum = 31;
} else if(month === 'April' || month === 'June' || month === 'September' || month === 'November') {
dayNum = 30;
} else {
// If month is February, calculate whether it is a leap year or not
var year = yearSelect.value;
var leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
dayNum = leap ? 29 : 28;
}
// inject the right number of new <option> elements into the day <select>
for(i = 1; i <= dayNum; i++) {
var option = document.createElement('option');
option.textContent = i;
daySelect.appendChild(option);
}
// if previous day has already been set, set daySelect's value
// to that day, to avoid the day jumping back to 1 when you
// change the year
if(previousDay) {
daySelect.value = previousDay;
// If the previous day was set to a high number, say 31, and then
// you chose a month with less total days in it (e.g. February),
// this part of the code ensures that the highest day available
// is selected, rather than showing a blank daySelect
if(daySelect.value === "") {
daySelect.value = previousDay - 1;
}
if(daySelect.value === "") {
daySelect.value = previousDay - 2;
}
if(daySelect.value === "") {
daySelect.value = previousDay - 3;
}
}
}
function populateYears() {
// get this year as a number
var date = new Date();
var year = date.getFullYear();
// Make this year, and the 100 years before it available in the year <select>
for(var i = 0; i <= 100; i++) {
var option = document.createElement('option');
option.textContent = year-i;
yearSelect.appendChild(option);
}
}
// when the month or year <select> values are changed, rerun populateDays()
// in case the change affected the number of available days
yearSelect.onchange = function() {
populateDays(monthSelect.value);
}
monthSelect.onchange = function() {
populateDays(monthSelect.value);
}
//preserve day selection
var previousDay;
// update what day has been set to previously
// see end of populateDays() for usage
daySelect.onchange = function() {
previousDay = daySelect.value;
}
Примечание: Remember that some years have 53 weeks in them (see Weeks per year)! You’ll need to take this into consideration when developing production apps.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- The generic
<input>
element and the interface used to manipulate it,HTMLInputElement
- Date and Time picker tutorial (en-US)
It is impossible to change the format
We have to differentiate between the over the wire format and the browser’s presentation format.
Wire format
The HTML5 date input specification refers to the RFC 3339 specification, which specifies a full-date format equal to: yyyy-mm-dd
. See section 5.6 of the RFC 3339 specification for more details.
This format is used by the value
HTML attribute and DOM property and is the one used when doing an ordinary form submission.
Presentation format
Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see here). They all display a date picker and format the text in the input field.
Desktop devices
For Chrome, Firefox, and Opera, the formatting of the input field’s text is based on the browser’s language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us
will be shown 01/30/2019
instead of the format they are accustomed to: 30-01-2019
.
Internet Explorer 9, 10, and 11 display a text input field with the wire format.
Mobile devices
Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I’ve not been able to verify this.
answered Mar 1, 2012 at 15:59
David WalschotsDavid Walschots
12k5 gold badges37 silver badges58 bronze badges
12
Since this question was asked quite a few things have happened in the web realm, and one of the most exciting is the landing of web components. Now you can solve this issue elegantly with a custom HTML5 element designed to suit your needs. If you wish to override/change the workings of any html tag just build yours playing with the shadow dom.
The good news is that there’s already a lot of boilerplate available so most likely you won’t need to come up with a solution from scratch. Just check what people are building and get ideas from there.
You can start with a simple (and working) solution like datetime-input for polymer that allows you to use a tag like this one:
<date-input date="{{date}}" timezone="[[timezone]]"></date-input>
or you can get creative and pop-up complete date-pickers styled as you wish, with the formatting and locales you desire, callbacks, and your long list of options (you’ve got a whole custom API at your disposal!)
Standards-compliant, no hacks.
Double-check the available polyfills, what browsers/versions they support, and if it covers enough % of your user base… It’s 2018, so chances are it’ll surely cover most of your users.
Hope it helps!
Peter Krebs
3,5082 gold badges16 silver badges29 bronze badges
answered Aug 21, 2015 at 22:01
sdudesdude
7,9392 gold badges21 silver badges24 bronze badges
8
As previously mentioned it is officially not possible to change the format. However it is possible to style the field, so (with a little JS help) it displays the date in a format we desire. Some of the possibilities to manipulate the date input is lost this way, but if the desire to force the format is greater, this solution might be a way. A date fields stays only like that:
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
The rest is a bit of CSS and JS: http://jsfiddle.net/g7mvaosL/
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
input {
position: relative;
width: 150px; height: 20px;
color: white;
}
input:before {
position: absolute;
top: 3px; left: 3px;
content: attr(data-date);
display: inline-block;
color: black;
}
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
It works nicely on Chrome for desktop, and Safari on iOS (especially desirable, since native date manipulators on touch screens are unbeatable IMHO). Didn’t check for others, but don’t expect to fail on any Webkit.
Mark Amery
137k78 gold badges401 silver badges450 bronze badges
answered Jul 1, 2015 at 13:14
pmuchapmucha
1,1971 gold badge7 silver badges3 bronze badges
11
It’s important to distinguish two different formats:
- The RFC 3339/ISO 8601 «wire format»: YYYY-MM-DD. According to the HTML5 specification, this is the format that must be used for the input’s value upon form submission or when requested via the DOM API. It is locale and region independent.
- The format displayed by the user interface control and accepted as user input. Browser vendors are encouraged to follow the user’s preferences selection. For example, on Mac OS with the region «United States» selected in the Language & Text preferences pane, Chrome 20 uses the format «m/d/yy».
The HTML5 specification does not include any means of overriding or manually specifying either format.
answered Jul 9, 2012 at 18:11
JohnJohn
29k11 gold badges77 silver badges79 bronze badges
3
I found a way to change format, it’s a tricky way, I just changed the appearance of the date input fields using just a CSS code.
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
input[type="date"]::-webkit-datetime-edit-year-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 56px;
}
input[type="date"]::-webkit-datetime-edit-month-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 26px;
}
input[type="date"]::-webkit-datetime-edit-day-field{
position: absolute !important;
color:#000;
padding: 2px;
left: 4px;
}
<input type="date" value="2019-12-07">
answered Dec 7, 2019 at 10:32
2
I believe the browser will use the local date format. Don’t think it’s possible to change. You could of course use a custom date picker.
answered Sep 10, 2011 at 13:39
Michael MiorMichael Mior
27.7k8 gold badges88 silver badges112 bronze badges
3
Google Chrome in its last beta version finally uses the input type=date
, and the format is DD-MM-YYYY
.
So there must be a way to force a specific format. I’m developing a HTML5 web page and the date searches now fail with different formats.
random
9,72610 gold badges69 silver badges82 bronze badges
answered Jun 16, 2012 at 15:30
TuramarthTuramarth
1631 silver badge2 bronze badges
5
I searched this issue 2 years ago, and my google searches leads me again to this question.
Don’t waste your time trying to handle this with pure JavaScript. I wasted my time trying to make it dd/mm/yyyy
. There’s no complete solutions that fits with all browsers. So I recommend to use momentJS / jQuery datepicker or tell your client to work with the default date format instead
answered Apr 22, 2020 at 17:18
Ali Al AmineAli Al Amine
1,5254 gold badges34 silver badges56 bronze badges
Browsers obtain the date-input format from user’s system date format.
(Tested in supported browsers, Chrome, Edge.)
As there is no standard defined by specs as of now to change the style of date control, it~s not possible to implement the same in browsers.
Users can type a date value into the text field of an input[type=date] with the date format shown in the box as gray text. This format is obtained from the operating system’s setting. Web authors have no way to change the date format because there currently is no standards to specify the format.
So no need to change it, if we don’t change anything, users will see the date-input’s format same as they have configured in the system/device settings and which they are comfortable with or matches with their locale.
Remember, this is just the UI format on the screen which users see, in your JavaScript/backend you can always keep your desired format to work with.
To change the format in Chrome (e.g. from US «MM/DD/YYYY» to «DD/MM/YYYY») you go to >Settings >Advanced >Add language (choose English UK). Then:
The browser gets restarted and you will find date input fields like this: ´25/01/2022
Refer google developers page on same.
WHATWG git hub query on same
Test using below date input:
<input type="date" id="dob" value=""/>
answered May 26, 2018 at 19:23
Rahul R.Rahul R.
5,7273 gold badges26 silver badges38 bronze badges
10
Try this if you need a quick solution To make yyyy-mm-dd go «dd- Sep -2016»
1) Create near your input one span class (act as label)
2) Update the label everytime your date is changed by user, or when need to load from data.
Works for webkit browser mobiles and pointer-events for IE11+ requires jQuery and Jquery Date
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px", top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
#date_input{text-indent: -500px;height:25px; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="d M y" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
answered Jun 22, 2015 at 17:32
MiguelMiguel
3,2432 gold badges32 silver badges28 bronze badges
2
After having read lots of discussions, I have prepared a simple solution but I don’t want to use lots of Jquery and CSS, just some javascript.
HTML Code:
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
CSS Code:
#dt {
text-indent: -500px;
height: 25px;
width: 200px;
}
Javascript Code :
function mydate() {
//alert("");
document.getElementById("dt").hidden = false;
document.getElementById("ndt").hidden = true;
}
function mydate1() {
d = new Date(document.getElementById("dt").value);
dt = d.getDate();
mn = d.getMonth();
mn++;
yy = d.getFullYear();
document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
document.getElementById("ndt").hidden = false;
document.getElementById("dt").hidden = true;
}
Output:
ChrisW
4,9437 gold badges55 silver badges89 bronze badges
answered Sep 2, 2015 at 7:40
ashish bhattashish bhatt
3,0415 gold badges25 silver badges23 bronze badges
As said, the <input type=date ... >
is not fully implemented in most browsers, so let’s talk about webkit like browsers (chrome).
Using linux, you can change it by changing the environment variable LANG
, LC_TIME
don’t seems to work(for me at least).
You can type locale
in a terminal to see your current values. I think the same concept can be applied to IOS.
eg:
Using:
LANG=en_US.UTF-8 /opt/google/chrome/chrome
The date is showed as mm/dd/yyyy
Using:
LANG=pt_BR /opt/google/chrome/chrome
The date is showed as dd/mm/yyyy
You can use http://lh.2xlibre.net/locale/pt_BR/ (change pt_BR
by your locale) to create you own custom locale and format your dates as you want.
A nice more advanced reference on how change default system date is:
How to change date formats on Ubuntu
and
https://askubuntu.com/questions/21316/how-can-i-customize-a-system-locale
You can see you real current date format using date
:
$ date +%x
01-06-2015
But as LC_TIME
and d_fmt
seems to be rejected by chrome ( and I think it’s a bug in webkit or chrome ), sadly it don’t work. :'(
So, unfortunately the response, is IF LANG
environment variable do not solve your problem, there is no way yet.
answered Jun 1, 2015 at 13:28
tonton
3,6291 gold badge39 silver badges40 bronze badges
1
It’s not possible to change web-kit browsers use user’s computer or mobiles default date format.
But if you can use jquery and jquery UI there is a date-picker which is designable and can be shown in any format as the developer wants.
the link to the jquery UI date-picker is
on this page http://jqueryui.com/datepicker/ you can find demo as well as code and documentation or documentation link
Edit:-I find that chrome uses language settings that are by default equal to system settings but the user can change them but developer can’t force users to do so so you have to use other js solutions like I tell you can search the web with queries like javascript date-pickers or jquery date-picker
answered Jun 4, 2014 at 7:55
Since the post is active 2 Months ago. so I thought to give my input as well.
In my case i recieve date from a card reader which comes in dd/mm/yyyy format.
what i do.
E.g.
var d="16/09/2019" // date received from card
function filldate(){
document.getElementById('cardexpirydate').value=d.split('/').reverse().join("-");
}
<input type="date" id="cardexpirydate">
<br /><br />
<input type="button" value="fill the date" onclick="filldate();">
what the code do:
- it splits the date which i get as dd/mm/yyyy (using split()) on basis of «/» and makes an array,
- it then reverse the array (using reverse()) since the date input supports the reverse
of what i get. - then it joins (using join())the array to a string according the
format required by the input field
All this is done in a single line.
i thought this will help some one so i wrote this.
answered Sep 16, 2019 at 8:00
1
I adjusted the code from Miguel to make it easier to understand
and I want to share it with people who have problems like me.
Try this for easy and quick way
$("#datePicker").on("change", function(e) {
displayDateFormat($(this), '#datePickerLbl', $(this).val());
});
function displayDateFormat(thisElement, datePickerLblId, dateValue) {
$(thisElement).css("color", "rgba(0,0,0,0)")
.siblings(`${datePickerLblId}`)
.css({
position: "absolute",
left: "10px",
top: "3px",
width: $(this).width()
})
.text(dateValue.length == 0 ? "" : (`${getDateFormat(new Date(dateValue))}`));
}
function getDateFormat(dateValue) {
let d = new Date(dateValue);
// this pattern dd/mm/yyyy
// you can set pattern you need
let dstring = `${("0" + d.getDate()).slice(-2)}/${("0" + (d.getMonth() + 1)).slice(-2)}/${d.getFullYear()}`;
return dstring;
}
.date-selector {
position: relative;
}
.date-selector>input[type=date] {
text-indent: -500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selector">
<input id="datePicker" class="form-control" type="date" onkeydown="return false" />
<span id="datePickerLbl" style="pointer-events: none;"></span>
</div>
answered Feb 9, 2021 at 9:54
A3IOUA3IOU
2491 gold badge3 silver badges11 bronze badges
NEW in Firefox (since unknown version), in Settings > Language, they have added an option: Use your operating system settings for “Spanish (Spain)” to format dates, times, numbers, and measurements
This option will use the Operating System’s locale to display dates! Too bad it does not come enabled by default (maybe from a fresh install it does?)
answered Sep 29, 2021 at 14:49
andreszsandreszs
2,8363 gold badges25 silver badges33 bronze badges
3
Angular devs (and maybe others) could consider this partial solution.
My strategy was to detect the focus state of the input field, and switch between date and text type accordingly. The obvious downside is that the date format will change on input focus.
It’s not perfect but insures a decent level of consistency especially if you have some dates displayed as text and also some date inputs in your web app. It’s not going to be very helpful if you have just one date input.
<input class="form-control"
[type]="myInputFocus ? 'date' : 'text'"
id="myInput"
name="myInput"
#myInput="ngModel"
[(ngModel)]="myDate"
(focus)="myInputFocus = true"
(blur)="myInputFocus = false">
And simply declare myInputFocus = false
at the beginning of you component class.
Obviously point myDate
to your desired control.
answered Feb 9, 2022 at 23:20
Thanks to @safi eddine and @Hezbullah Shah
Datepicker with VanillaJS and CSS.
CSS — STYLE:
/*================== || Date Picker ||=======================================================================================*/
/*-------Removes the // Before dd - day------------------------*/
input[type="date"]::-webkit-datetime-edit-text
{
color: transparent;
}
/*------- DatePicker ------------------------*/
input[type="date"] {
background-color: aqua;
border-radius: 4px;
border: 1px solid #8c8c8c;
font-weight: 900;
}
/*------- DatePicker - Focus ------------------------*/
input[type="date"]:focus
{
outline: none;
box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);
}
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
/*------- Year ------------------------*/
input[type="date"]::-webkit-datetime-edit-year-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 56px;
}
/*------- Month ------------------------*/
input[type="date"]::-webkit-datetime-edit-month-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 26px;
}
/*------- Day ------------------------*/
input[type="date"]::-webkit-datetime-edit-day-field {
position: absolute !important;
color: #000;
padding: 2px;
left: 4px;
}
JAVASCRIPT:
// ================================ || Format Date Picker || ===========================================================
function GetFormatedDate(datePickerID)
{
let rawDate = document.getElementById(datePickerID).value; // Get the Raw Date
return rawDate.split('-').reverse().join("-"); // Reverse the date
}
USING:
document.getElementById('datePicker').onchange = function () { alert(GetFormatedDate('datePicker')); }; // The datepickerID
answered May 31, 2021 at 19:01
Stefan27Stefan27
6277 silver badges18 bronze badges
const birthday = document.getElementById("birthday");
const button = document.getElementById("wishBtn");
button.addEventListener("click", () => {
let dateValue = birthday.value;
// Changing format :)
dateValue = dateValue.split('-').reverse().join('-');
alert(`Happy birthday king/Queen of ${dateValue}`);
});
<input type="date" id="birthday" name="birthday" value="2022-10-10"/>
<button id="wishBtn">Clik Me</button>
answered Jul 7, 2022 at 12:33
1
Not really no.
Hackable but very slim & customizable solution would be to:
- Hide date input (CSS visibility: hidden) (still shows calendar popup tho)
- Put a text input on top of it
- On text input click, use JS to get date input element & call .showPicker()
- store date picker value elsewhere
- show value in your custom format you want in the text input
Here’s some sample react code:
<div style={{ width: "100%", position: "relative" }}>
<input type="date" className={`form-control ${props.filters[dateFromAccessor] ? '' : 'bh-hasNoValue'}`} id={`${accessor}-date-from`} placeholder='from'
value={toDate(props.filters[dateFromAccessor])} style={{ marginRight: 0, visibility: "hidden" }}
onChange={e => {
props.setFilters({ ...props.filters, [dateFromAccessor]: inputsValueToNumber(e) })
}} />
<input type="text" className="form-control" readOnly
style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", backgroundColor: "white" }}
value={toDate(props.filters[dateFromAccessor])}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
(document.getElementById(`${accessor}-date-from`) as any)?.showPicker();
}}></input>
</div>
answered Jan 19 at 12:34
I know it’s an old post but it come as first suggestion in google search, short answer no, recommended answer user a custom date piker , the correct answer that i use is using a text box to simulate the date input and do any format you want, here is the code
<html>
<body>
date :
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
<input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">▼</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
window.onload =function(){
var input = document.createElement('input');
input.setAttribute('type','date');
input.setAttribute('value', 'some text');
if(input.value === "some text"){
allDates = document.getElementsByClassName("xDateContainer");
matchEnterdDate=1;
for (var i = 0; i < allDates.length; i++) {
allDates[i].style.opacity = "1";
}
}
}
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
var date = new Date(xObj.value);
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(month!='NaN'){
document.getElementById(xTraget).value=day+" / "+month+" / "+year;
}else{
if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
}
}
</script>
</body>
</html>
1- please note that this method only work for browser that support date type.
2- the first function in JS code is for browser that don’t support date type and set the look to a normal text input.
3- if you will use this code for multiple date inputs in your page please change the ID «xTime» of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.
4-on the second function you can use any format you want instead of day+» / «+month+» / «+year for example year+» / «+month+» / «+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.
answered Sep 21, 2018 at 17:32
shadyshady
92 bronze badges
It is impossible to change the format
We have to differentiate between the over the wire format and the browser’s presentation format.
Wire format
The HTML5 date input specification refers to the RFC 3339 specification, which specifies a full-date format equal to: yyyy-mm-dd
. See section 5.6 of the RFC 3339 specification for more details.
This format is used by the value
HTML attribute and DOM property and is the one used when doing an ordinary form submission.
Presentation format
Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see here). They all display a date picker and format the text in the input field.
Desktop devices
For Chrome, Firefox, and Opera, the formatting of the input field’s text is based on the browser’s language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us
will be shown 01/30/2019
instead of the format they are accustomed to: 30-01-2019
.
Internet Explorer 9, 10, and 11 display a text input field with the wire format.
Mobile devices
Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I’ve not been able to verify this.
answered Mar 1, 2012 at 15:59
David WalschotsDavid Walschots
12k5 gold badges37 silver badges58 bronze badges
12
Since this question was asked quite a few things have happened in the web realm, and one of the most exciting is the landing of web components. Now you can solve this issue elegantly with a custom HTML5 element designed to suit your needs. If you wish to override/change the workings of any html tag just build yours playing with the shadow dom.
The good news is that there’s already a lot of boilerplate available so most likely you won’t need to come up with a solution from scratch. Just check what people are building and get ideas from there.
You can start with a simple (and working) solution like datetime-input for polymer that allows you to use a tag like this one:
<date-input date="{{date}}" timezone="[[timezone]]"></date-input>
or you can get creative and pop-up complete date-pickers styled as you wish, with the formatting and locales you desire, callbacks, and your long list of options (you’ve got a whole custom API at your disposal!)
Standards-compliant, no hacks.
Double-check the available polyfills, what browsers/versions they support, and if it covers enough % of your user base… It’s 2018, so chances are it’ll surely cover most of your users.
Hope it helps!
Peter Krebs
3,5082 gold badges16 silver badges29 bronze badges
answered Aug 21, 2015 at 22:01
sdudesdude
7,9392 gold badges21 silver badges24 bronze badges
8
As previously mentioned it is officially not possible to change the format. However it is possible to style the field, so (with a little JS help) it displays the date in a format we desire. Some of the possibilities to manipulate the date input is lost this way, but if the desire to force the format is greater, this solution might be a way. A date fields stays only like that:
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
The rest is a bit of CSS and JS: http://jsfiddle.net/g7mvaosL/
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
input {
position: relative;
width: 150px; height: 20px;
color: white;
}
input:before {
position: absolute;
top: 3px; left: 3px;
content: attr(data-date);
display: inline-block;
color: black;
}
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
It works nicely on Chrome for desktop, and Safari on iOS (especially desirable, since native date manipulators on touch screens are unbeatable IMHO). Didn’t check for others, but don’t expect to fail on any Webkit.
Mark Amery
137k78 gold badges401 silver badges450 bronze badges
answered Jul 1, 2015 at 13:14
pmuchapmucha
1,1971 gold badge7 silver badges3 bronze badges
11
It’s important to distinguish two different formats:
- The RFC 3339/ISO 8601 «wire format»: YYYY-MM-DD. According to the HTML5 specification, this is the format that must be used for the input’s value upon form submission or when requested via the DOM API. It is locale and region independent.
- The format displayed by the user interface control and accepted as user input. Browser vendors are encouraged to follow the user’s preferences selection. For example, on Mac OS with the region «United States» selected in the Language & Text preferences pane, Chrome 20 uses the format «m/d/yy».
The HTML5 specification does not include any means of overriding or manually specifying either format.
answered Jul 9, 2012 at 18:11
JohnJohn
29k11 gold badges77 silver badges79 bronze badges
3
I found a way to change format, it’s a tricky way, I just changed the appearance of the date input fields using just a CSS code.
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
input[type="date"]::-webkit-datetime-edit-year-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 56px;
}
input[type="date"]::-webkit-datetime-edit-month-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 26px;
}
input[type="date"]::-webkit-datetime-edit-day-field{
position: absolute !important;
color:#000;
padding: 2px;
left: 4px;
}
<input type="date" value="2019-12-07">
answered Dec 7, 2019 at 10:32
2
I believe the browser will use the local date format. Don’t think it’s possible to change. You could of course use a custom date picker.
answered Sep 10, 2011 at 13:39
Michael MiorMichael Mior
27.7k8 gold badges88 silver badges112 bronze badges
3
Google Chrome in its last beta version finally uses the input type=date
, and the format is DD-MM-YYYY
.
So there must be a way to force a specific format. I’m developing a HTML5 web page and the date searches now fail with different formats.
random
9,72610 gold badges69 silver badges82 bronze badges
answered Jun 16, 2012 at 15:30
TuramarthTuramarth
1631 silver badge2 bronze badges
5
I searched this issue 2 years ago, and my google searches leads me again to this question.
Don’t waste your time trying to handle this with pure JavaScript. I wasted my time trying to make it dd/mm/yyyy
. There’s no complete solutions that fits with all browsers. So I recommend to use momentJS / jQuery datepicker or tell your client to work with the default date format instead
answered Apr 22, 2020 at 17:18
Ali Al AmineAli Al Amine
1,5254 gold badges34 silver badges56 bronze badges
Browsers obtain the date-input format from user’s system date format.
(Tested in supported browsers, Chrome, Edge.)
As there is no standard defined by specs as of now to change the style of date control, it~s not possible to implement the same in browsers.
Users can type a date value into the text field of an input[type=date] with the date format shown in the box as gray text. This format is obtained from the operating system’s setting. Web authors have no way to change the date format because there currently is no standards to specify the format.
So no need to change it, if we don’t change anything, users will see the date-input’s format same as they have configured in the system/device settings and which they are comfortable with or matches with their locale.
Remember, this is just the UI format on the screen which users see, in your JavaScript/backend you can always keep your desired format to work with.
To change the format in Chrome (e.g. from US «MM/DD/YYYY» to «DD/MM/YYYY») you go to >Settings >Advanced >Add language (choose English UK). Then:
The browser gets restarted and you will find date input fields like this: ´25/01/2022
Refer google developers page on same.
WHATWG git hub query on same
Test using below date input:
<input type="date" id="dob" value=""/>
answered May 26, 2018 at 19:23
Rahul R.Rahul R.
5,7273 gold badges26 silver badges38 bronze badges
10
Try this if you need a quick solution To make yyyy-mm-dd go «dd- Sep -2016»
1) Create near your input one span class (act as label)
2) Update the label everytime your date is changed by user, or when need to load from data.
Works for webkit browser mobiles and pointer-events for IE11+ requires jQuery and Jquery Date
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px", top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
#date_input{text-indent: -500px;height:25px; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="d M y" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
answered Jun 22, 2015 at 17:32
MiguelMiguel
3,2432 gold badges32 silver badges28 bronze badges
2
After having read lots of discussions, I have prepared a simple solution but I don’t want to use lots of Jquery and CSS, just some javascript.
HTML Code:
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
CSS Code:
#dt {
text-indent: -500px;
height: 25px;
width: 200px;
}
Javascript Code :
function mydate() {
//alert("");
document.getElementById("dt").hidden = false;
document.getElementById("ndt").hidden = true;
}
function mydate1() {
d = new Date(document.getElementById("dt").value);
dt = d.getDate();
mn = d.getMonth();
mn++;
yy = d.getFullYear();
document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
document.getElementById("ndt").hidden = false;
document.getElementById("dt").hidden = true;
}
Output:
ChrisW
4,9437 gold badges55 silver badges89 bronze badges
answered Sep 2, 2015 at 7:40
ashish bhattashish bhatt
3,0415 gold badges25 silver badges23 bronze badges
As said, the <input type=date ... >
is not fully implemented in most browsers, so let’s talk about webkit like browsers (chrome).
Using linux, you can change it by changing the environment variable LANG
, LC_TIME
don’t seems to work(for me at least).
You can type locale
in a terminal to see your current values. I think the same concept can be applied to IOS.
eg:
Using:
LANG=en_US.UTF-8 /opt/google/chrome/chrome
The date is showed as mm/dd/yyyy
Using:
LANG=pt_BR /opt/google/chrome/chrome
The date is showed as dd/mm/yyyy
You can use http://lh.2xlibre.net/locale/pt_BR/ (change pt_BR
by your locale) to create you own custom locale and format your dates as you want.
A nice more advanced reference on how change default system date is:
How to change date formats on Ubuntu
and
https://askubuntu.com/questions/21316/how-can-i-customize-a-system-locale
You can see you real current date format using date
:
$ date +%x
01-06-2015
But as LC_TIME
and d_fmt
seems to be rejected by chrome ( and I think it’s a bug in webkit or chrome ), sadly it don’t work. :'(
So, unfortunately the response, is IF LANG
environment variable do not solve your problem, there is no way yet.
answered Jun 1, 2015 at 13:28
tonton
3,6291 gold badge39 silver badges40 bronze badges
1
It’s not possible to change web-kit browsers use user’s computer or mobiles default date format.
But if you can use jquery and jquery UI there is a date-picker which is designable and can be shown in any format as the developer wants.
the link to the jquery UI date-picker is
on this page http://jqueryui.com/datepicker/ you can find demo as well as code and documentation or documentation link
Edit:-I find that chrome uses language settings that are by default equal to system settings but the user can change them but developer can’t force users to do so so you have to use other js solutions like I tell you can search the web with queries like javascript date-pickers or jquery date-picker
answered Jun 4, 2014 at 7:55
Since the post is active 2 Months ago. so I thought to give my input as well.
In my case i recieve date from a card reader which comes in dd/mm/yyyy format.
what i do.
E.g.
var d="16/09/2019" // date received from card
function filldate(){
document.getElementById('cardexpirydate').value=d.split('/').reverse().join("-");
}
<input type="date" id="cardexpirydate">
<br /><br />
<input type="button" value="fill the date" onclick="filldate();">
what the code do:
- it splits the date which i get as dd/mm/yyyy (using split()) on basis of «/» and makes an array,
- it then reverse the array (using reverse()) since the date input supports the reverse
of what i get. - then it joins (using join())the array to a string according the
format required by the input field
All this is done in a single line.
i thought this will help some one so i wrote this.
answered Sep 16, 2019 at 8:00
1
I adjusted the code from Miguel to make it easier to understand
and I want to share it with people who have problems like me.
Try this for easy and quick way
$("#datePicker").on("change", function(e) {
displayDateFormat($(this), '#datePickerLbl', $(this).val());
});
function displayDateFormat(thisElement, datePickerLblId, dateValue) {
$(thisElement).css("color", "rgba(0,0,0,0)")
.siblings(`${datePickerLblId}`)
.css({
position: "absolute",
left: "10px",
top: "3px",
width: $(this).width()
})
.text(dateValue.length == 0 ? "" : (`${getDateFormat(new Date(dateValue))}`));
}
function getDateFormat(dateValue) {
let d = new Date(dateValue);
// this pattern dd/mm/yyyy
// you can set pattern you need
let dstring = `${("0" + d.getDate()).slice(-2)}/${("0" + (d.getMonth() + 1)).slice(-2)}/${d.getFullYear()}`;
return dstring;
}
.date-selector {
position: relative;
}
.date-selector>input[type=date] {
text-indent: -500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selector">
<input id="datePicker" class="form-control" type="date" onkeydown="return false" />
<span id="datePickerLbl" style="pointer-events: none;"></span>
</div>
answered Feb 9, 2021 at 9:54
A3IOUA3IOU
2491 gold badge3 silver badges11 bronze badges
NEW in Firefox (since unknown version), in Settings > Language, they have added an option: Use your operating system settings for “Spanish (Spain)” to format dates, times, numbers, and measurements
This option will use the Operating System’s locale to display dates! Too bad it does not come enabled by default (maybe from a fresh install it does?)
answered Sep 29, 2021 at 14:49
andreszsandreszs
2,8363 gold badges25 silver badges33 bronze badges
3
Angular devs (and maybe others) could consider this partial solution.
My strategy was to detect the focus state of the input field, and switch between date and text type accordingly. The obvious downside is that the date format will change on input focus.
It’s not perfect but insures a decent level of consistency especially if you have some dates displayed as text and also some date inputs in your web app. It’s not going to be very helpful if you have just one date input.
<input class="form-control"
[type]="myInputFocus ? 'date' : 'text'"
id="myInput"
name="myInput"
#myInput="ngModel"
[(ngModel)]="myDate"
(focus)="myInputFocus = true"
(blur)="myInputFocus = false">
And simply declare myInputFocus = false
at the beginning of you component class.
Obviously point myDate
to your desired control.
answered Feb 9, 2022 at 23:20
Thanks to @safi eddine and @Hezbullah Shah
Datepicker with VanillaJS and CSS.
CSS — STYLE:
/*================== || Date Picker ||=======================================================================================*/
/*-------Removes the // Before dd - day------------------------*/
input[type="date"]::-webkit-datetime-edit-text
{
color: transparent;
}
/*------- DatePicker ------------------------*/
input[type="date"] {
background-color: aqua;
border-radius: 4px;
border: 1px solid #8c8c8c;
font-weight: 900;
}
/*------- DatePicker - Focus ------------------------*/
input[type="date"]:focus
{
outline: none;
box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);
}
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
/*------- Year ------------------------*/
input[type="date"]::-webkit-datetime-edit-year-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 56px;
}
/*------- Month ------------------------*/
input[type="date"]::-webkit-datetime-edit-month-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 26px;
}
/*------- Day ------------------------*/
input[type="date"]::-webkit-datetime-edit-day-field {
position: absolute !important;
color: #000;
padding: 2px;
left: 4px;
}
JAVASCRIPT:
// ================================ || Format Date Picker || ===========================================================
function GetFormatedDate(datePickerID)
{
let rawDate = document.getElementById(datePickerID).value; // Get the Raw Date
return rawDate.split('-').reverse().join("-"); // Reverse the date
}
USING:
document.getElementById('datePicker').onchange = function () { alert(GetFormatedDate('datePicker')); }; // The datepickerID
answered May 31, 2021 at 19:01
Stefan27Stefan27
6277 silver badges18 bronze badges
const birthday = document.getElementById("birthday");
const button = document.getElementById("wishBtn");
button.addEventListener("click", () => {
let dateValue = birthday.value;
// Changing format :)
dateValue = dateValue.split('-').reverse().join('-');
alert(`Happy birthday king/Queen of ${dateValue}`);
});
<input type="date" id="birthday" name="birthday" value="2022-10-10"/>
<button id="wishBtn">Clik Me</button>
answered Jul 7, 2022 at 12:33
1
Not really no.
Hackable but very slim & customizable solution would be to:
- Hide date input (CSS visibility: hidden) (still shows calendar popup tho)
- Put a text input on top of it
- On text input click, use JS to get date input element & call .showPicker()
- store date picker value elsewhere
- show value in your custom format you want in the text input
Here’s some sample react code:
<div style={{ width: "100%", position: "relative" }}>
<input type="date" className={`form-control ${props.filters[dateFromAccessor] ? '' : 'bh-hasNoValue'}`} id={`${accessor}-date-from`} placeholder='from'
value={toDate(props.filters[dateFromAccessor])} style={{ marginRight: 0, visibility: "hidden" }}
onChange={e => {
props.setFilters({ ...props.filters, [dateFromAccessor]: inputsValueToNumber(e) })
}} />
<input type="text" className="form-control" readOnly
style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", backgroundColor: "white" }}
value={toDate(props.filters[dateFromAccessor])}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
(document.getElementById(`${accessor}-date-from`) as any)?.showPicker();
}}></input>
</div>
answered Jan 19 at 12:34
I know it’s an old post but it come as first suggestion in google search, short answer no, recommended answer user a custom date piker , the correct answer that i use is using a text box to simulate the date input and do any format you want, here is the code
<html>
<body>
date :
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
<input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">▼</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
window.onload =function(){
var input = document.createElement('input');
input.setAttribute('type','date');
input.setAttribute('value', 'some text');
if(input.value === "some text"){
allDates = document.getElementsByClassName("xDateContainer");
matchEnterdDate=1;
for (var i = 0; i < allDates.length; i++) {
allDates[i].style.opacity = "1";
}
}
}
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
var date = new Date(xObj.value);
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(month!='NaN'){
document.getElementById(xTraget).value=day+" / "+month+" / "+year;
}else{
if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
}
}
</script>
</body>
</html>
1- please note that this method only work for browser that support date type.
2- the first function in JS code is for browser that don’t support date type and set the look to a normal text input.
3- if you will use this code for multiple date inputs in your page please change the ID «xTime» of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.
4-on the second function you can use any format you want instead of day+» / «+month+» / «+year for example year+» / «+month+» / «+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.
answered Sep 21, 2018 at 17:32
shadyshady
92 bronze badges
It is impossible to change the format
We have to differentiate between the over the wire format and the browser’s presentation format.
Wire format
The HTML5 date input specification refers to the RFC 3339 specification, which specifies a full-date format equal to: yyyy-mm-dd
. See section 5.6 of the RFC 3339 specification for more details.
This format is used by the value
HTML attribute and DOM property and is the one used when doing an ordinary form submission.
Presentation format
Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see here). They all display a date picker and format the text in the input field.
Desktop devices
For Chrome, Firefox, and Opera, the formatting of the input field’s text is based on the browser’s language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us
will be shown 01/30/2019
instead of the format they are accustomed to: 30-01-2019
.
Internet Explorer 9, 10, and 11 display a text input field with the wire format.
Mobile devices
Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I’ve not been able to verify this.
answered Mar 1, 2012 at 15:59
David WalschotsDavid Walschots
12k5 gold badges37 silver badges58 bronze badges
12
Since this question was asked quite a few things have happened in the web realm, and one of the most exciting is the landing of web components. Now you can solve this issue elegantly with a custom HTML5 element designed to suit your needs. If you wish to override/change the workings of any html tag just build yours playing with the shadow dom.
The good news is that there’s already a lot of boilerplate available so most likely you won’t need to come up with a solution from scratch. Just check what people are building and get ideas from there.
You can start with a simple (and working) solution like datetime-input for polymer that allows you to use a tag like this one:
<date-input date="{{date}}" timezone="[[timezone]]"></date-input>
or you can get creative and pop-up complete date-pickers styled as you wish, with the formatting and locales you desire, callbacks, and your long list of options (you’ve got a whole custom API at your disposal!)
Standards-compliant, no hacks.
Double-check the available polyfills, what browsers/versions they support, and if it covers enough % of your user base… It’s 2018, so chances are it’ll surely cover most of your users.
Hope it helps!
Peter Krebs
3,5082 gold badges16 silver badges29 bronze badges
answered Aug 21, 2015 at 22:01
sdudesdude
7,9392 gold badges21 silver badges24 bronze badges
8
As previously mentioned it is officially not possible to change the format. However it is possible to style the field, so (with a little JS help) it displays the date in a format we desire. Some of the possibilities to manipulate the date input is lost this way, but if the desire to force the format is greater, this solution might be a way. A date fields stays only like that:
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
The rest is a bit of CSS and JS: http://jsfiddle.net/g7mvaosL/
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
input {
position: relative;
width: 150px; height: 20px;
color: white;
}
input:before {
position: absolute;
top: 3px; left: 3px;
content: attr(data-date);
display: inline-block;
color: black;
}
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
It works nicely on Chrome for desktop, and Safari on iOS (especially desirable, since native date manipulators on touch screens are unbeatable IMHO). Didn’t check for others, but don’t expect to fail on any Webkit.
Mark Amery
137k78 gold badges401 silver badges450 bronze badges
answered Jul 1, 2015 at 13:14
pmuchapmucha
1,1971 gold badge7 silver badges3 bronze badges
11
It’s important to distinguish two different formats:
- The RFC 3339/ISO 8601 «wire format»: YYYY-MM-DD. According to the HTML5 specification, this is the format that must be used for the input’s value upon form submission or when requested via the DOM API. It is locale and region independent.
- The format displayed by the user interface control and accepted as user input. Browser vendors are encouraged to follow the user’s preferences selection. For example, on Mac OS with the region «United States» selected in the Language & Text preferences pane, Chrome 20 uses the format «m/d/yy».
The HTML5 specification does not include any means of overriding or manually specifying either format.
answered Jul 9, 2012 at 18:11
JohnJohn
29k11 gold badges77 silver badges79 bronze badges
3
I found a way to change format, it’s a tricky way, I just changed the appearance of the date input fields using just a CSS code.
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
input[type="date"]::-webkit-datetime-edit-year-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 56px;
}
input[type="date"]::-webkit-datetime-edit-month-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 26px;
}
input[type="date"]::-webkit-datetime-edit-day-field{
position: absolute !important;
color:#000;
padding: 2px;
left: 4px;
}
<input type="date" value="2019-12-07">
answered Dec 7, 2019 at 10:32
2
I believe the browser will use the local date format. Don’t think it’s possible to change. You could of course use a custom date picker.
answered Sep 10, 2011 at 13:39
Michael MiorMichael Mior
27.7k8 gold badges88 silver badges112 bronze badges
3
Google Chrome in its last beta version finally uses the input type=date
, and the format is DD-MM-YYYY
.
So there must be a way to force a specific format. I’m developing a HTML5 web page and the date searches now fail with different formats.
random
9,72610 gold badges69 silver badges82 bronze badges
answered Jun 16, 2012 at 15:30
TuramarthTuramarth
1631 silver badge2 bronze badges
5
I searched this issue 2 years ago, and my google searches leads me again to this question.
Don’t waste your time trying to handle this with pure JavaScript. I wasted my time trying to make it dd/mm/yyyy
. There’s no complete solutions that fits with all browsers. So I recommend to use momentJS / jQuery datepicker or tell your client to work with the default date format instead
answered Apr 22, 2020 at 17:18
Ali Al AmineAli Al Amine
1,5254 gold badges34 silver badges56 bronze badges
Browsers obtain the date-input format from user’s system date format.
(Tested in supported browsers, Chrome, Edge.)
As there is no standard defined by specs as of now to change the style of date control, it~s not possible to implement the same in browsers.
Users can type a date value into the text field of an input[type=date] with the date format shown in the box as gray text. This format is obtained from the operating system’s setting. Web authors have no way to change the date format because there currently is no standards to specify the format.
So no need to change it, if we don’t change anything, users will see the date-input’s format same as they have configured in the system/device settings and which they are comfortable with or matches with their locale.
Remember, this is just the UI format on the screen which users see, in your JavaScript/backend you can always keep your desired format to work with.
To change the format in Chrome (e.g. from US «MM/DD/YYYY» to «DD/MM/YYYY») you go to >Settings >Advanced >Add language (choose English UK). Then:
The browser gets restarted and you will find date input fields like this: ´25/01/2022
Refer google developers page on same.
WHATWG git hub query on same
Test using below date input:
<input type="date" id="dob" value=""/>
answered May 26, 2018 at 19:23
Rahul R.Rahul R.
5,7273 gold badges26 silver badges38 bronze badges
10
Try this if you need a quick solution To make yyyy-mm-dd go «dd- Sep -2016»
1) Create near your input one span class (act as label)
2) Update the label everytime your date is changed by user, or when need to load from data.
Works for webkit browser mobiles and pointer-events for IE11+ requires jQuery and Jquery Date
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px", top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
#date_input{text-indent: -500px;height:25px; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="d M y" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
answered Jun 22, 2015 at 17:32
MiguelMiguel
3,2432 gold badges32 silver badges28 bronze badges
2
After having read lots of discussions, I have prepared a simple solution but I don’t want to use lots of Jquery and CSS, just some javascript.
HTML Code:
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
CSS Code:
#dt {
text-indent: -500px;
height: 25px;
width: 200px;
}
Javascript Code :
function mydate() {
//alert("");
document.getElementById("dt").hidden = false;
document.getElementById("ndt").hidden = true;
}
function mydate1() {
d = new Date(document.getElementById("dt").value);
dt = d.getDate();
mn = d.getMonth();
mn++;
yy = d.getFullYear();
document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
document.getElementById("ndt").hidden = false;
document.getElementById("dt").hidden = true;
}
Output:
ChrisW
4,9437 gold badges55 silver badges89 bronze badges
answered Sep 2, 2015 at 7:40
ashish bhattashish bhatt
3,0415 gold badges25 silver badges23 bronze badges
As said, the <input type=date ... >
is not fully implemented in most browsers, so let’s talk about webkit like browsers (chrome).
Using linux, you can change it by changing the environment variable LANG
, LC_TIME
don’t seems to work(for me at least).
You can type locale
in a terminal to see your current values. I think the same concept can be applied to IOS.
eg:
Using:
LANG=en_US.UTF-8 /opt/google/chrome/chrome
The date is showed as mm/dd/yyyy
Using:
LANG=pt_BR /opt/google/chrome/chrome
The date is showed as dd/mm/yyyy
You can use http://lh.2xlibre.net/locale/pt_BR/ (change pt_BR
by your locale) to create you own custom locale and format your dates as you want.
A nice more advanced reference on how change default system date is:
How to change date formats on Ubuntu
and
https://askubuntu.com/questions/21316/how-can-i-customize-a-system-locale
You can see you real current date format using date
:
$ date +%x
01-06-2015
But as LC_TIME
and d_fmt
seems to be rejected by chrome ( and I think it’s a bug in webkit or chrome ), sadly it don’t work. :'(
So, unfortunately the response, is IF LANG
environment variable do not solve your problem, there is no way yet.
answered Jun 1, 2015 at 13:28
tonton
3,6291 gold badge39 silver badges40 bronze badges
1
It’s not possible to change web-kit browsers use user’s computer or mobiles default date format.
But if you can use jquery and jquery UI there is a date-picker which is designable and can be shown in any format as the developer wants.
the link to the jquery UI date-picker is
on this page http://jqueryui.com/datepicker/ you can find demo as well as code and documentation or documentation link
Edit:-I find that chrome uses language settings that are by default equal to system settings but the user can change them but developer can’t force users to do so so you have to use other js solutions like I tell you can search the web with queries like javascript date-pickers or jquery date-picker
answered Jun 4, 2014 at 7:55
Since the post is active 2 Months ago. so I thought to give my input as well.
In my case i recieve date from a card reader which comes in dd/mm/yyyy format.
what i do.
E.g.
var d="16/09/2019" // date received from card
function filldate(){
document.getElementById('cardexpirydate').value=d.split('/').reverse().join("-");
}
<input type="date" id="cardexpirydate">
<br /><br />
<input type="button" value="fill the date" onclick="filldate();">
what the code do:
- it splits the date which i get as dd/mm/yyyy (using split()) on basis of «/» and makes an array,
- it then reverse the array (using reverse()) since the date input supports the reverse
of what i get. - then it joins (using join())the array to a string according the
format required by the input field
All this is done in a single line.
i thought this will help some one so i wrote this.
answered Sep 16, 2019 at 8:00
1
I adjusted the code from Miguel to make it easier to understand
and I want to share it with people who have problems like me.
Try this for easy and quick way
$("#datePicker").on("change", function(e) {
displayDateFormat($(this), '#datePickerLbl', $(this).val());
});
function displayDateFormat(thisElement, datePickerLblId, dateValue) {
$(thisElement).css("color", "rgba(0,0,0,0)")
.siblings(`${datePickerLblId}`)
.css({
position: "absolute",
left: "10px",
top: "3px",
width: $(this).width()
})
.text(dateValue.length == 0 ? "" : (`${getDateFormat(new Date(dateValue))}`));
}
function getDateFormat(dateValue) {
let d = new Date(dateValue);
// this pattern dd/mm/yyyy
// you can set pattern you need
let dstring = `${("0" + d.getDate()).slice(-2)}/${("0" + (d.getMonth() + 1)).slice(-2)}/${d.getFullYear()}`;
return dstring;
}
.date-selector {
position: relative;
}
.date-selector>input[type=date] {
text-indent: -500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selector">
<input id="datePicker" class="form-control" type="date" onkeydown="return false" />
<span id="datePickerLbl" style="pointer-events: none;"></span>
</div>
answered Feb 9, 2021 at 9:54
A3IOUA3IOU
2491 gold badge3 silver badges11 bronze badges
NEW in Firefox (since unknown version), in Settings > Language, they have added an option: Use your operating system settings for “Spanish (Spain)” to format dates, times, numbers, and measurements
This option will use the Operating System’s locale to display dates! Too bad it does not come enabled by default (maybe from a fresh install it does?)
answered Sep 29, 2021 at 14:49
andreszsandreszs
2,8363 gold badges25 silver badges33 bronze badges
3
Angular devs (and maybe others) could consider this partial solution.
My strategy was to detect the focus state of the input field, and switch between date and text type accordingly. The obvious downside is that the date format will change on input focus.
It’s not perfect but insures a decent level of consistency especially if you have some dates displayed as text and also some date inputs in your web app. It’s not going to be very helpful if you have just one date input.
<input class="form-control"
[type]="myInputFocus ? 'date' : 'text'"
id="myInput"
name="myInput"
#myInput="ngModel"
[(ngModel)]="myDate"
(focus)="myInputFocus = true"
(blur)="myInputFocus = false">
And simply declare myInputFocus = false
at the beginning of you component class.
Obviously point myDate
to your desired control.
answered Feb 9, 2022 at 23:20
Thanks to @safi eddine and @Hezbullah Shah
Datepicker with VanillaJS and CSS.
CSS — STYLE:
/*================== || Date Picker ||=======================================================================================*/
/*-------Removes the // Before dd - day------------------------*/
input[type="date"]::-webkit-datetime-edit-text
{
color: transparent;
}
/*------- DatePicker ------------------------*/
input[type="date"] {
background-color: aqua;
border-radius: 4px;
border: 1px solid #8c8c8c;
font-weight: 900;
}
/*------- DatePicker - Focus ------------------------*/
input[type="date"]:focus
{
outline: none;
box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);
}
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
/*------- Year ------------------------*/
input[type="date"]::-webkit-datetime-edit-year-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 56px;
}
/*------- Month ------------------------*/
input[type="date"]::-webkit-datetime-edit-month-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 26px;
}
/*------- Day ------------------------*/
input[type="date"]::-webkit-datetime-edit-day-field {
position: absolute !important;
color: #000;
padding: 2px;
left: 4px;
}
JAVASCRIPT:
// ================================ || Format Date Picker || ===========================================================
function GetFormatedDate(datePickerID)
{
let rawDate = document.getElementById(datePickerID).value; // Get the Raw Date
return rawDate.split('-').reverse().join("-"); // Reverse the date
}
USING:
document.getElementById('datePicker').onchange = function () { alert(GetFormatedDate('datePicker')); }; // The datepickerID
answered May 31, 2021 at 19:01
Stefan27Stefan27
6277 silver badges18 bronze badges
const birthday = document.getElementById("birthday");
const button = document.getElementById("wishBtn");
button.addEventListener("click", () => {
let dateValue = birthday.value;
// Changing format :)
dateValue = dateValue.split('-').reverse().join('-');
alert(`Happy birthday king/Queen of ${dateValue}`);
});
<input type="date" id="birthday" name="birthday" value="2022-10-10"/>
<button id="wishBtn">Clik Me</button>
answered Jul 7, 2022 at 12:33
1
Not really no.
Hackable but very slim & customizable solution would be to:
- Hide date input (CSS visibility: hidden) (still shows calendar popup tho)
- Put a text input on top of it
- On text input click, use JS to get date input element & call .showPicker()
- store date picker value elsewhere
- show value in your custom format you want in the text input
Here’s some sample react code:
<div style={{ width: "100%", position: "relative" }}>
<input type="date" className={`form-control ${props.filters[dateFromAccessor] ? '' : 'bh-hasNoValue'}`} id={`${accessor}-date-from`} placeholder='from'
value={toDate(props.filters[dateFromAccessor])} style={{ marginRight: 0, visibility: "hidden" }}
onChange={e => {
props.setFilters({ ...props.filters, [dateFromAccessor]: inputsValueToNumber(e) })
}} />
<input type="text" className="form-control" readOnly
style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", backgroundColor: "white" }}
value={toDate(props.filters[dateFromAccessor])}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
(document.getElementById(`${accessor}-date-from`) as any)?.showPicker();
}}></input>
</div>
answered Jan 19 at 12:34
I know it’s an old post but it come as first suggestion in google search, short answer no, recommended answer user a custom date piker , the correct answer that i use is using a text box to simulate the date input and do any format you want, here is the code
<html>
<body>
date :
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
<input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">▼</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
window.onload =function(){
var input = document.createElement('input');
input.setAttribute('type','date');
input.setAttribute('value', 'some text');
if(input.value === "some text"){
allDates = document.getElementsByClassName("xDateContainer");
matchEnterdDate=1;
for (var i = 0; i < allDates.length; i++) {
allDates[i].style.opacity = "1";
}
}
}
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
var date = new Date(xObj.value);
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(month!='NaN'){
document.getElementById(xTraget).value=day+" / "+month+" / "+year;
}else{
if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
}
}
</script>
</body>
</html>
1- please note that this method only work for browser that support date type.
2- the first function in JS code is for browser that don’t support date type and set the look to a normal text input.
3- if you will use this code for multiple date inputs in your page please change the ID «xTime» of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.
4-on the second function you can use any format you want instead of day+» / «+month+» / «+year for example year+» / «+month+» / «+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.
answered Sep 21, 2018 at 17:32
shadyshady
92 bronze badges
For Helppo users, I wanted to offer a way to edit date and datetime values more conveniently than with a plain text input. This is of course nothing new; most sites use datepickers for this purpose.
As a developer, there are plenty of ready-made options to choose from. For example, react-datepicker (which almost doubled the bundle size in the case of Helppo) with ~720k weekly installs. Or pikaday (which has promising principles, although a lot of issues and PRs open) with ~210k weekly installs.
I wanted to see if just a regular <input type="date">
could do the job. I had a couple of requirements and/or liberties, depending on how you want to look at it:
-
Because Helppo should (a) be able to display a date value in any format coming from the user’s database, and (b) the format in which the user wants to input a new value should not be restricted, I wanted the datepicker to be a separate element next to a plain text field.
-
The datepicker element should be styleable via CSS.
-
I didn’t consider a time picker necessary. From my experience, time picker UIs are generally more difficult to use than a regular text field. (If Helppo users begin requesting this functionality, then I will of course look into it.)
With these in mind I started experimenting and browsing StackOverflow.
Default appearance of <input type="date">
MDN offers an incredibly helpful wiki page around <input type="date">
, and it includes screenshots of the datepicker on various browsers. I added a couple of mine to the bottom of the list.
One thing I found out is that in Safari (and in IE, I hear) a date input acts like a regular text input, and has no datepicker.
On Chrome:
Screenshot by Mozilla Contributors is licensed under CC-BY-SA 2.5.
On Firefox:
Screenshot by Mozilla Contributors is licensed under CC-BY-SA 2.5.
On Edge:
Screenshot by Mozilla Contributors is licensed under CC-BY-SA 2.5.
On Chrome (MacOS):
Screenshot by me.
On Safari (MacOS):
None! No datepicker for Safari.
Screenshot by me.
As can be seen in the above screenshots, the default datepicker is a text input where the date is displayed in a locale-specific format. Either clicking on the input, or on a calendar-icon inside it, opens a datepicked popup. This is similar to how datepicker JS libraries work.
To highlight the different components:
Whereas JS libraries allow for customization of styles and functionality, in the case of <input type="date">
you don’t really get that. There’s no toggle to enable week numbers or year dropdowns; the browser will either render such things, or it won’t.
Default functionality of <input type="date">
Another concern was if the input value, when read via JavaScript, would be consistent between browsers.
In the case of Helppo I always wanted it in the same format (YYYY-MM-DD), but obviously it wouldn’t really matter what the format was as long as it could be consistently parsed.
Luckily this is not a problem! As per the MDN page, reading input.value
should result in a consistent format:
const dateInput = document.querySelector('.date-input');
console.log(dateInput.value); // "2020-10-26"
Enter fullscreen mode
Exit fullscreen mode
This is regardless of the fact that the visible format is locale-based in the input.
To be sure, I tested and verified it in various browsers on MacOS.
Based on this result, we can confidently listen to onchange
event on a <input type="date">
and get the same date format back no matter the platform.
Customizing the input
First of all, if your application needs a datepicker, I would strongly recommend just using <input type="date">
as seen above! There really should be a specific reason for including a datepicker library when the out-of-the-box solution works so well.
As noted in the beginning, however, for Helppo I had the requirement that the datepicker should be an extra button next to a regular text input. In this fashion:
So I needed to transform <input type="date">
into a button-like element.
Our starting point:
- Some browsers (Firefox, Edge) don’t have a toggle, and just open the popup when you click the input
- Some browsers (Chrome) open the popup when you click a toggle-button
- Some browsers (Safari, IE) don’t open a popup at all
For point #1, we should be able to just make a date input invisible and stretch it on top of the toggle we want to display. That way, when the user clicks the toggle, they actually click the date input which triggers the popup.
For point #2, we should try to do the same but for the toggle-part of the date input. I started searching and landed on this answer in StackOverflow, which does that for webkit browsers.
For point #3, we should not show the toggle at all because clicking on it won’t do anything. Ideally this would be done without user-agent sniffing or any other method of hard-coded browser detection.
Making it happen (the markup)
Here’s how we’ll structure the toggle-button in the HTML:
<span class="datepicker-toggle">
<span class="datepicker-toggle-button"></span>
<input type="date" class="datepicker-input">
</span>
Enter fullscreen mode
Exit fullscreen mode
Note on accessibility: because we’re using just spans with no text content, the only actionable element in this piece of HTML is the input. The focus flow of the document is the same as if there just was a regular input here. If you use different kind of elements (e.g. an
<img>
), make sure to ensure your element stays accessible.
And here are the base styles of the wrapper element and the visual button we want to show:
.datepicker-toggle {
display: inline-block;
position: relative;
width: 18px;
height: 19px;
}
.datepicker-toggle-button {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-image: url('data:image/svg+xml;base64,...');
}
Enter fullscreen mode
Exit fullscreen mode
Note on
.datepicker-toggle-button
: this is the element you would style entirely based on your application. In this case I’m just using a background-image for simplicity.
At this point we just have the date input visible next to the button-element, as it resides in the DOM:
Here begins the browser-specific CSS for stretching the actionable part of the input over the visible button.
Based on the previously mentioned SO answer:
.datepicker-input {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
box-sizing: border-box;
}
.datepicker-input::-webkit-calendar-picker-indicator {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
cursor: pointer;
}
Enter fullscreen mode
Exit fullscreen mode
Works for Chrome (MacOS), which normally has the toggle:
Works for Firefox (MacOS), which doesn’t have a toggle:
I also asked a friend to verify on Firefox on Windows, and they sent me a similar screenshot to the above.
I wasn’t able to verify it on Edge, but based on the fact that on Edge clicking the input triggers the popup, it should work similarly to Firefox because we stretch the invisible input over the whole button.
Finally, I tested it also on iOS Safari, and the datepicker opened as expected:
Detecting browsers that don’t have a datepicker popup
As mentioned above, some browsers (Safari, IE) don’t have the datepicker functionality built-in. Instead a date input acts like a regular text input. For these browsers we shouldn’t show the button at all, because it would just sit there without doing anything.
I looked into detecting the browser support automatically. Some ideas I researched:
- Detecting the existence of specific shadow DOM. See the below screenshot. It would’ve been great if we could check the existence of datepicker-specific elements (e.g.
input.shadowRoot.querySelector("[pseudo='-webkit-calendar-picker-indicator']")
), but unfortunately that’s not possible in the case of an input element (shadowRoot
isnull
; read more at MDN). I’m not aware of any workaround for this.
-
Reading
document.styleSheets
to figure out if our pseudo-element CSS selector has been successfully applied. Now, this was a wild idea based on no prior code I’d ever seen, and of course it yielded no results.CSSStyleSheet
does not contain any information about how the style was applied or if it was valid. -
Continued on the previous point… how about trying to read the styles of the pseudo element, and noticing differences in the results based on the browser? I added an obscure enough CSS style for the pseudo-element:
.datepicker-input::-webkit-calendar-picker-indicator { font-variant-caps: titling-caps; }
and then tried to read it:window.getComputedStyle($0, '::-webkit-calendar-picker-indicator').fontVariantCaps
(also with variations of and the lack of colons). Unfortunately this would always return the style value of the input element, not the pseudo element. This is probably because, again, we can’t access the shadow DOM. The above works for e.g.:before
pseudo-elements, but doesn’t seem to work for our use case. -
Checking if
<input type="date">
value is automatically sanitized by the browser. This turned out to be the winner. In hindsight I should’ve checked this one first, but it seemed obvious to me that this would not work, because I assumed that a date input would still have formatting/sanitization. Turns out that’s not the case.
So in the end checking for datepicker support is as simple as setting an input value and checking if the browser accepted it:
const input = document.createElement('input');
input.type = 'date';
input.value = 'invalid date value';
const isSupported = input.value !== 'invalid date value';
Enter fullscreen mode
Exit fullscreen mode
I verified that this works in Safari.
Listening for onchange
event
All that’s left is to update the value of a text input when the user chooses a date from the popup. That is very straight-forward:
const textInput = document.querySelector('.text-input');
const dateInput = document.querySelector('.datepicker-input');
dateInput.addEventListener('change', event => {
textInput.value = event.target.value;
// Reset the value so the picker always
// opens in a fresh state regardless of
// what was last picked
event.target.value = '';
});
Enter fullscreen mode
Exit fullscreen mode
An alternative to resetting the date input value is to keep it in sync with the text input, which gets a bit more complicated but is still quite simple:
dateInput.addEventListener('change', event => {
textInput.value = event.target.value;
});
textInput.addEventListener('input', event => {
const value = textInput.value.trim();
dateInput.value = value.match(/^d{4}-d{2}-d{2}$/) ? value : '';
});
Enter fullscreen mode
Exit fullscreen mode
GitHub repository
I’ve packaged this solution into a reusable mini-library here:
- https://github.com/codeclown/native-datepicker
Also published on npm as native-datepicker
:
- https://www.npmjs.com/package/native-datepicker
The repository contains examples of how to use the code in both a React codebase as well as in plain vanilla JavaScript. A glimpse of the API:
const picker = new NativeDatepicker({
onChange: value => {
// ...
},
});
someElement.appendNode(picker.element);
Enter fullscreen mode
Exit fullscreen mode
Included is also a ready-made React-component:
<NativeDatepicker
className="custom-class"
value={value}
onChange={value => {
// ...
}}
/>
Enter fullscreen mode
Exit fullscreen mode
It is also aware of datetime inputs (i.e. if the text input contains a value like «2020-10-26 23:35:00», the library will replace just the date-portion of it upon change).
It would be cool if you found use for the package. If there’s any issues, please file an issue in the GitHub repository!
Thanks
Thanks for reading!
Thank you also to MDN and the StackOverflow commenters for the building blocks of this exploration.
If you haven’t already, feel free to check out Helppo, for which I originally built this component. Helppo is a CLI-tool (written in NodeJS) which allows you to spin up an admin interface for your database. Just run npx helppo-cli --help
to get started.
Я создал кнопку выбора даты в качестве кнопки, и, когда она зависает, она выглядит беспорядочной в браузере Chrome. может быть причина только из-за его поведения по умолчанию в браузерах, но могу ли я изменить этот эффект наведения на хром?
Изображение в Fire Fox:
По умолчанию <input type=date>
Кнопка <input type=date>
Изображение в Chrome:
По умолчанию <input type=date>
(при наведении)
Кнопка <input type=date>
(при наведении указателя мыши)
Есть ли способ удалить этот эффект зависания на chrome?
Ввод по умолчанию:
<input type="date" id="myInput">
ИЗОБРАЖЕН С CSS:
.date-picker-button {
background: #8DBF42;
color: #fff;
position: relative;
cursor: pointer;
margin-bottom: 10px;
border: 2px solid #8DBF42;
font-size: 14px;
padding: 12px;
border-radius: 3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
-o-border-radius: 3px;
width: 300px;
}
.input-group {
position: relative;
border: 2px solid #cdd7e1;
margin-bottom: 10px;
display: block !important;
width: 300px;
border: none;
}
.date-picker-button .date-picker-input {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: 0;
background: #8DBF42;
border: none;
width: 300px;
padding-left: 55px;
}
.fa.fa-angle-down {
float: right;
color: white;
font-size: 20px !important;
font-weight: 600;
top: 0px !important;
position: relative;
margin-right: 20px;
}
.fa-calendar-o {
color: white !important;
z-index: 1;
top: 0px !important;
position: relative !important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="date-picker-button input-group">
<i class="fa fa-calendar-o" aria-hidden="true"></i>
<span>Select Date</span>
<input class="input-startdate date-picker-input hasDatepicker" name="effdate" id="dp1523936970319" aria-required="true" required="" type="date">
<i class="fa fa-angle-down" aria-hidden="true"></i>
</div>