Элементы <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 badges451 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 badges451 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 badges451 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
<input type=»date»>
<input>
Элементы <input> type="date"
создают поля ввода, которые позволяют пользователю вводить дату, либо с текстовым полем, которое проверяет ввод, либо с помощью специального интерфейса выбора даты.
Полученное значение включает год, месяц и день, но не время. Время и дату и время-местные типы входов поддержка времени и дата + ввод времени.
Try it
Пользовательский интерфейс ввода обычно варьируется от браузера к браузеру; Дополнительные сведения см . в разделе Совместимость с браузерами. В неподдерживаемых браузерах элемент управления изящно деградирует до <input type="text">
.
Value
Строка, представляющая дату, введенную во входные данные. Дата форматируется в соответствии со стандартом ISO8601, описанным в разделе Формат строк даты .
Вы можете установить значение по умолчанию для ввода с датой внутри атрибута value
, например:
<input type="date" value="2017-06-01">
Примечание . Отображаемый формат даты будет отличаться от фактического value
— отображаемая дата форматируется в зависимости от языкового стандарта браузера пользователя , но анализируемое value
всегда имеет формат yyyy-mm-dd
.
Вы можете получить и установить значение даты в JavaScript с HTMLInputElement
value
и valueAsNumber
свойствами. Например:
const dateControl = document.querySelector('input[type="date"]'); dateControl.value = '2017-06-01'; console.log(dateControl.value); console.log(dateControl.valueAsNumber);
Этот код находит первый <input>
элемент , чей type
является date
, и устанавливает его значение в 2017-06-01
(1 июня 2017 года). Затем он считывает это значение обратно в строковом и числовом форматах.
Additional attributes
Атрибуты, общие для всех элементов <input>
, также применимы к вводу date
, но могут не влиять на ее представление. Например size
и placeholder
могут не работать. date
имеют следующие дополнительные атрибуты.
max
Самая последняя дата для принятия. Если value
введенное в элемент, встречается позже, элемент не проходит проверку ограничения . Если значение атрибута max
не является возможной строкой даты в формате yyyy-mm-dd
, то элемент не имеет максимального значения даты.
Если установлены оба атрибута max
и min
, это значение должно быть строкой даты, более поздней или равной строке в атрибуте min
.
min
Самая ранняя дата принятия. Если value
введенное в элемент, встречается заранее, элемент не проходит проверку ограничения . Если значение атрибута min
не является возможной строкой даты в формате yyyy-mm-dd
, то элемент не имеет минимального значения даты.
Если установлены атрибуты max
и min
, это значение должно быть строкой даты, которая раньше или равнялась строке в атрибуте max
.
step
Атрибут step
— это число, указывающее степень детализации, которой должно придерживаться значение, или специальное значение any
, описанное ниже. Действительны только значения, которые равны основанию для шага ( min
, если указано, value
в противном случае, и соответствующее значение по умолчанию, если ни одно из них не указано).
Строковое значение any
означает, что шаг не подразумевается, и разрешено любое значение (за исключением других ограничений, таких как min
и max
).
Примечание. Когда данные, введенные пользователем, не соответствуют пошаговой конфигурации, пользовательский агент может округлить до ближайшего допустимого значения, предпочитая числа в положительном направлении, когда есть два одинаково близких варианта.
Для входов date
значение step
указывается в днях; и рассматривается как количество миллисекунд, равное 86 400 000 раз больше значения step
(базовое числовое значение выражается в миллисекундах). Значение step
умолчанию — 1, что означает 1 день.
Примечание: указание any
в качестве значения для step
имеет тот же эффект, что и 1
для входных данных date
.
Использование ввода даты
Ввод даты обеспечивает простой интерфейс для выбора дат и нормализует формат данных,отправляемых на сервер,независимо от локали пользователя.
В этом разделе мы рассмотрим основные, а затем более сложные варианты использования <input type="date">
.
Основные виды использования даты
Самое простое использование <input type="date">
включает один <input>
в сочетании с его <label>
, как показано ниже:
<form action="https://example.com"> <label> Enter your birthday: <input type="date" name="bday"> </label> <p><button>Submit</button></p> </form>
Этот HTML-код отправляет введенную дату под ключом bday
на https://example.com
— в результате получается URL-адрес вида https://example.com/?bday=1955-06-08
.
Установка максимальных и минимальных дат
Вы можете использовать атрибуты min
и max
, чтобы ограничить даты, которые могут быть выбраны пользователем. В следующем примере мы устанавливаем минимальную дату 2017-04-01
и максимальную дату 2017-04-30
:
<form> <label>Choose your preferred party date: <input type="date" name="party" min="2017-04-01" max="2017-04-30"> </label> </form>
В результате можно будет выбрать только дни апреля 2017 года-части текстового поля месяц и год будут недоступны для редактирования,а даты за пределами апреля 2017 года нельзя будет выбрать в виджете picker.
Примечание. У вас должна быть возможность использовать атрибут step
для изменения количества дней, на которые выполняется переход каждый раз при увеличении даты (например, чтобы можно было выбирать только субботу). Однако на момент написания этого, похоже, не было ни в одной реализации.
Контролируемый размер входа
<input type="date">
не поддерживает атрибуты изменения размера формы, такие как size
. Предпочитайте CSS для его размера.
Validation
По умолчанию <input type="date">
не проверяет введенное значение за пределами его формата. Интерфейсы, как правило, не позволяют вам вводить что-либо, кроме даты, что полезно, но вы можете оставить поле пустым или ввести недопустимую дату в браузерах, где ввод возвращается к вводу text
(например, 32 апреля). .
Если вы используете min
и max
для ограничения доступных дат (см. Установка максимальной и минимальной дат ), поддерживающие браузеры будут отображать ошибку, если вы попытаетесь отправить дату, выходящую за границы. Однако вам необходимо дважды проверить отправленные результаты, чтобы убедиться, что значение находится в пределах этих дат, если средство выбора даты не полностью поддерживается на устройстве пользователя.
Вы также можете использовать атрибут required
, чтобы сделать заполнение даты обязательным — будет отображаться ошибка, если вы попытаетесь отправить пустое поле даты. Это должно работать в большинстве браузеров, даже если они возвращаются к текстовому вводу.
Давайте рассмотрим пример минимальной и максимальной дат,а также сделаем поле обязательным для заполнения:
<form> <label> Choose your preferred party date (required, April 1st to 20th): <input type="date" name="party" min="2017-04-01" max="2017-04-20" required> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </form>
Если вы попытаетесь отправить форму с неполной датой (или с датой,выходящей за пределы установленных границ),браузер выдаст ошибку.Попробуйте поиграть с примером сейчас:
Вот CSS, использованный в приведенном выше примере. Мы делаем использование :valid
и :invalid
псевдо-элементы , чтобы добавить значок рядом с полем ввода, в зависимости от того или не действительно текущее значения. Нам пришлось поместить значок на <span>
рядом с вводом, а не на самом вводе, потому что в Chrome, по крайней мере, сгенерированное содержимое ввода помещается внутри элемента управления формой и не может быть стилизовано или эффективно показано.
label { display: flex; align-items: center; } span::after { padding-left: 5px; } input:invalid + span::after { content: '✖'; } input:valid+span::after { content: '✓'; }
Предупреждение: проверка формы на стороне клиента не заменяет проверку на сервере. Кто-то может легко изменить HTML или полностью обойти ваш HTML и отправить данные прямо на ваш сервер. Если вашему серверу не удается проверить полученные данные, может произойти авария с данными, которые плохо отформатированы, слишком большие, неправильного типа и т. Д.
Поддержка браузера
Браузеры,не поддерживающие этот тип ввода,изящно переходят к текстовому вводу,но это создает проблемы с согласованностью пользовательского интерфейса (представленные элементы управления отличаются друг от друга)и обработкой данных.
Вторая проблема более серьезная; при поддержке ввода даты значение нормализуется в формате yyyy-mm-dd
. Но при вводе текста браузер не распознает, в каком формате должна быть дата, и существует множество различных форматов, в которых люди пишут даты. Например:
ddmmyyyy
dd/mm/yyyy
mm/dd/yyyy
dd-mm-yyyy
mm-dd-yyyy
Month dd, yyyy
Один из способов обойти это — атрибут pattern
во вводе даты. Несмотря на то, что средство выбора даты не использует его, резервный вариант ввода текста будет. Например, попробуйте просмотреть следующее в неподдерживаемом браузере:
<form> <label>Enter your birthday: <input type="date" name="bday" required pattern="d{4}-d{2}-d{2}"> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </form>
Если вы отправите его, вы увидите, что браузер отображает ошибку и выделяет ввод как недопустимый, если ваша запись не соответствует шаблону ####-##-##
(где #
— это цифра от 0 до 9 ). Конечно, это не мешает людям вводить неверные даты или неправильные форматы. Так что у нас все еще есть проблема.
На данный момент лучший способ работать с датами в формах в кросс-браузере — это дать пользователю возможность вводить день, месяц и год в отдельных элементах управления или использовать библиотеку JavaScript, такую как средство выбора даты jQuery .
Examples
В этом примере мы создаем 2 набора элементов пользовательского интерфейса для выбора дат: собственное средство выбора <input type="date">
и набор из 3 элементов <select>
для старых браузеров, которые не поддерживают собственный ввод даты.
HTML
HTML выглядит так:
<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>
Месяцы жестко закодированы (так как они всегда одни и те же),а значения дня и года динамически генерируются в зависимости от текущего выбранного месяца и года,а также текущего года (подробное описание работы этих функций см.в комментариях к коду ниже).
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date
HTML
-
<input type=»checkbox»>
Элементы <input> типа checkbox отображаются по умолчанию как флажки, которые отмечены (отмечены) при активации, как вы могли бы увидеть официальную правительственную газету.
-
<input type=»color»>
Элементы <input> типа color предоставляют пользовательский интерфейс, который позволяет указать либо с помощью визуального средства выбора, введя в текстовое поле шестнадцатеричный формат #rrggbb.
-
JavaScript
Другая часть кода, которая может представлять интерес, — это функция определения того, поддерживает ли браузер <input type=»date»>.
-
<input type=»datetime-local»>
Элементы <input> типа datetime-local создают элементы управления, которые позволяют пользователю легко вводить и год, и месяц, и день, и часы, и минуты.
<input>
elements of type="date"
create input fields that let the user enter a date, either with a textbox that validates the input or a special date picker interface.
The resulting value includes the year, month, and day, but not the time. The time and datetime-local input types support time and date+time input.
The source for this interactive example is stored in a GitHub repository. If you’d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
The input UI generally varies from browser to browser; see Browser compatibility for further details. In unsupported browsers, the control degrades gracefully to <input type="text">
.
Among browsers with custom interfaces for selecting dates are Chrome and Opera, whose data control looks like so:
The Edge date control looks like:
And the Firefox date control looks like this:
Value
A DOMString
representing the date entered in the input. The date is formatted according to ISO8601, described in Format of a valid date string in Date and time formats used in HTML.
You can set a default value for the input with a date inside the value
attribute, like so:
<input type="date" value="2017-06-01">
The displayed date format will differ from the actual value
— the displayed date is formatted based on the locale of the user’s browser, but the parsed value
is always formatted yyyy-mm-dd
.
You can get and set the date value in JavaScript with the input element’s value
and valueAsNumber
properties. For example:
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 UNIX timestamp
This code finds the first <input>
element whose type
is date
, and sets its value to 2017-06-01
(June 1st, 2017). It then reads that value back in string and number formats.
Additional attributes
Along with the attributes common to all <input>
elements, date
inputs have the following attributes:
Attribute | Description |
---|---|
max |
The latest acceptable date |
min |
The earliest acceptable date |
step |
The stepping interval, when clicking up and down spinner buttons and validating the date |
max
The latest date to accept. If the value
entered into the element occurs afterward, the element fails constraint validation. If the value of the max
attribute isn’t a possible date string in the format yyyy-mm-dd
, then the element has no maximum date value.
If both the max
and min
attributes are set, this value must be a date string later than or equal to the one in the min
attribute.
min
The earliest date to accept. If the value
entered into the element occurs beforehand, the element fails constraint validation. If the value of the min
attribute isn’t a possible date string in the format yyyy-mm-dd
, then the element has no minimum date value.
If both the max
and min
attributes are set, this value must be a date string earlier than or equal to the one in the max
attribute.
step
The step
attribute is a number that specifies the granularity that the value must adhere to, or the special value any
, which is described below. Only values which are equal to the basis for stepping (min
if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid.
A string value of any
means that no stepping is implied, and any value is allowed (barring other constraints, such as min
and max
).
Note: When the data entered by the user doesn’t adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.
For date
inputs, the value of step
is given in days; and is treated as a number of milliseconds equal to 86,400,000 times the step
value (the underlying numeric value is in milliseconds). The default value of step
is 1, indicating 1 day.
Specifying any
as the value for step
has the same effect as 1
for date
inputs.
Using date inputs
Date inputs sound convenient — they provide an easy interface for choosing dates, and they normalize the data format sent to the server regardless of the user’s locale. However, there are currently issues with <input type="date">
because of its limited browser support.
In this section, we’ll look at basic and then more complex uses of <input type="date">
, and offer advice on mitigating the browser support issue later (see Handling browser support).
Hopefully, over time browser support will become ubiquitous, and this problem will fade away.
Basic uses of date
The simplest use of <input type="date">
involves one <input>
combined with its <label>
, as seen below:
<form action="https://example.com"> <label> Enter your birthday: <input type="date" name="bday"> </label> <p><button>Submit</button></p> </form>
This HTML submits the entered date under the key bday
to https://example.com
— resulting in a URL like https://example.com/?bday=1955-06-08
.
Setting maximum and minimum dates
You can use the min
and max
attributes to restrict the dates that can be chosen by the user. In the following example, we set a minimum date of 2017-04-01
and a maximum date of 2017-04-30
:
<form> <label for="party">Choose your preferred party date: <input type="date" name="party" min="2017-04-01" max="2017-04-30"> </label> </form>
The result is that only days in April 2017 can be selected — the month and year parts of the textbox will be uneditable, and dates outside April 2017 can’t be selected in tte picker widget.
Note: You should be able to use the step
attribute to vary the number of days jumped each time the date is incremented (e.g. to only make Saturdays selectable). However, this does not seem to be in any implementation at the time of writing.
Controlling input size
<input type="date">
doesn’t support form sizing attributes such as size
. Prefer CSS for sizing it.
Validation
By default, <input type="date">
doesn’t validate the entered value beyond its format. The interfaces generally don’t let you enter anything that isn’t a date — which is helpful — but you can leave the field empty or enter an invalid date in browsers where the input falls back to type text
(like 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 out of bounds. However, you’ll need to double-check the submitted results to ensure the value is within these dates, if the date picker isn’t fully supported on the user’s device.
You can also use the required
attribute to make filling in the date mandatory — an error will be displayed if you try to submit an empty date field. This should work in most browsers, even if they fall back to a text input.
Let’s look at an example of minimum and maximum dates, and also made a field required:
<form> <label> Choose your preferred party date (required, April 1st to 20th): <input type="date" name="party" min="2017-04-01" max="2017-04-20" required> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </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. We make use of the :valid
and :invalid
pseudo-elements to add an icon next to the input, based on whether or not the current value is valid. We had to put the icon on a <span>
next to the input, not on the input itself, because in Chrome at least the input’s generated content is placed inside the form control, and can’t be styled or shown effectively.
label { display: flex; align-items: center; } span::after { padding-left: 5px; } input:invalid + span::after { content: '✖'; } input:valid+span::after { content: '✓'; }
Important: Client-side form validation is no substitute for validating on the server. It’s easy for someone to modify the HTML, or bypass your HTML entirely and submit the data directly to your server. If your server fails to validate the received data, disaster could strike with data that is badly-formatted, too large, of the wrong type, etc.
Handling browser support
As mentioned, the major problem with date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:
Unsupporting browsers gracefully degrade to a text input, but this creates problems in consistency of user interface (the presented controls are different) and data handling.
The second problem is the more serious one; with date input supported, the value is normalized to the format yyyy-mm-dd
. But with a text input, the browser has no recognition of what format the date should be in, and there are many different formats 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 the pattern
attribute on your date input. Even though the date picker doesn’t use it, the text input fallback will. For example, try viewing the following in a unsupporting browser:
<form> <label for="bday">Enter your birthday: <input type="date" name="bday" required pattern="d{4}-d{2}-d{2}"> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </form>
If you submit it, you’ll see that the browser displays an error and highlights the input as invalid if your entry doesn’t match the pattern ####-##-##
(where #
is a digit from 0 to 9). Of course, this doesn’t stop people from entering invalid dates, or incorrect formats. So we still have a problem.
At the moment, the best way to deal with dates in forms in a cross-browser way is to have the user enter the day, month, and year in separate controls, or to use a JavaScript library such as jQuery date picker.
Examples
In this example, we create 2 sets of UI elements for choosing dates: a native <input type="date">
picker and a set of 3 <select>
elements for older browsers that don’t support the native date 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.)
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, try setting its type
to date
, then immediately check what its type is — unsupporting browsers will return text
, because the date
type falls back to type text
. If <input type="date">
isn’t supported, we hide the native picker and show the fallback (<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'); try { test.type = 'date'; } catch (e) { console.log(e.description); } // 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 isLeap = new Date(year, 1, 29).getMonth() == 1; isLeap ? dayNum = 29 : dayNum = 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; }
Note: 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
Specification | Status | Comments |
---|---|---|
HTML Living Standard The definition of ‘<input type=»date»>’ in that specification. |
Living Standard | |
HTML5 The definition of ‘<input type=»date»>’ in that specification. |
Recommendation |
Browser compatibility
The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Firefox for Android | Opera for Android | Safari on iOS | Samsung Internet | |
type="date" |
Chrome Full support 20 |
Edge Full support 12 |
Firefox Full support 57 |
IE No support No |
Opera Full support 11 |
Safari No support No Notes
|
WebView Android Full support Yes |
Chrome Android Full support Yes |
Firefox Android Full support 57 |
Opera Android Full support 11 |
Safari iOS Full support 5 |
Samsung Internet Android Full support Yes |
Legend
Full support- Full support
No support- No support
- See implementation notes.
- See implementation notes.
See also
- The generic
<input>
element and the interface used to manipulate it,HTMLInputElement
- Date and Time picker tutorial
- Date and time formats used in HTML
- Compatibility of CSS properties
<input>
elements of type date
create input fields allowing a date to be easily entered — this includes year, month and day, but not time
.
The control’s UI varies in general from browser to browser; at the moment support is patchy, see Browser compatibility for further details. In unsupported browsers, the control degrades gracefully to a simple <input type="text">.
<input id="date" type="date">
For those of you not using a supporting browser, the Chrome/Opera date control looks like so:
and the Edge date control looks like this:
Value
A DOMString
representing the value of the date entered into the input. You can set a default value for the input by including a date inside the value
attribute, like so:
<input id="date" type="date" value="2017-06-01">
One thing to note is that the displayed date format differs from the actual value
— the displayed date format will be chosen based on the set locale of the user’s operating system, whereas the date value
is always formatted yyyy-mm-dd
.
You can also get and set the date value in JavaScript using the HTMLInputElement.value
property, for example:
var dateControl = document.querySelector('input[type="date"]'); dateControl.value = '2017-06-01';
Using date inputs
Date inputs sound convenient at first glance — they provide an easy UI for choosing dates, and they normalize the data format sent to the server, regardless of the user’s locale. However, there are issues with <input type="date">
because of the limited browser support.
We’ll look at basic and more complex uses of <input type="date">
, then offer advice on mitigating the browser support issue later on (see Handling browser support).
Basic uses of date
The simplest use of <input type="date">
involves a basic <input>
and <label>
element combination, as seen below:
<form> <div> <label for="bday">Enter your birthday:</label> <input type="date" id="bday" name="bday"> </div> </form>
Setting maximum and minimum dates
You can use the min
and max
attributes to restrict the dates that can be chosen by the user. In the following example we are setting a minimum date of 2017-04-01
and a maximum date of 2017-04-30
:
<form> <div> <label for="party">Choose your preferred party date:</label> <input type="date" id="party" name="party" min="2017-04-01" max="2017-04-30"> </div> </form>
The result here is that only days in April can be selected — only the «days» part of the text value will be editable, and dates outside April can’t be scrolled to in the datepicker widget.
Note: You should be able to use the step
attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing.
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 not fill in a date and submit, or enter an invalid date (e.g. the 32th of April).
If you use min
and max
to restrict the available dates (see anch(«Setting maximum and minimum dates»)), supporting browsers will display an error if you try to submit a date that is outside the set bounds.
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.
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 most serious — 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
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 you 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.
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 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.
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.)
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; (year - 2016) % 4 === 0 ? dayNum = 29 : dayNum = 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; }
Specifications
Specification | Status | Comments |
---|---|---|
WHATWG HTML Living Standard The definition of ‘<input type=»date»>’ in that specification. |
Living Standard | |
HTML5 The definition of ‘<input type=»date»>’ in that specification. |
Recommendation |
Browser compatibility
- Desktop
- Mobile
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 20 | 12 | No support[1] | No support | 10.62 | No support[2] |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | ? | 10.62 | 5 |
[1] This feature is implemented behind the preference dom.forms.datetime
since Gecko 51 (Firefox 51 / Thunderbird 51 / SeaMonkey 2.48), defaulting to false
. Since Gecko 55 it is enabled by default on Firefox Nightly (see bug 1366188). See also bug 888320 and TPE DOM/Date time input types.
[2] It is recognized but there is no UI.
See also
- The generic
<input>
element and the interface used to manipulate it,HTMLInputElement
- Date and Time picker tutorial