1113

By default, the input type="date" shows date as YYYY-MM-DD.

The question is, is it possible to force it's format to something like: DD-MM-YYYY?

9
  • 13
    Google has created a FAQ for Chrome: developers.google.com/web/updates/2012/08/… So format is based on OS's locale setting. Commented Oct 2, 2015 at 1:50
  • 10
    I waste my time trying to make it dd/mm/yyyy. just use another library like moment or jQuery datepicker
    – Ali
    Commented Apr 22, 2020 at 17:19
  • 9
    If anyone out there is looking for a quick fix such as adding the attribute format="yyyy-mm-dd". There is nothing like that in the specs. Commented Aug 25, 2021 at 7:53
  • 4
    Is it possible to overload the HTMLInputElement to provide it different locale? Please check my question here: stackoverflow.com/q/68536503/96313 Commented Aug 27, 2021 at 16:57
  • Firefox added an option to use the OS' locale to display dates, check my answer. I know it does not solve the root issue, but for developers is a nice option.
    – andreszs
    Commented Sep 29, 2021 at 14:51

23 Answers 23

815

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.

12
  • 8
    @AllanKimmerJensen though I understand your thoughts. I believe the decision to use the format specified in RFC3339 is a correct one, as it does not create a coupling between HTML and JavaScript. As for your second point, I'd feel that from a usability perspective, it would make sense for the user to see the calendar according to his regional preferences. Commented Jan 30, 2013 at 10:47
  • 34
    If the app is pt_BR, I expect a pt_BR input. my system settings doesn't matter. HTML5 need some way to enforce locale.
    – iurisilvio
    Commented Jan 26, 2015 at 19:14
  • 13
    I use Spanish locale for date/currency settings as I am based in Spain, yet my first language is English and I'm used to a USA keyboard layout so I use English/USA keyboard. My customers are French-speaking European.... I wish I could hint to Chrome etc. to stop displaying dates in USA mm-dd-yyyy format!
    – Luke H
    Commented Aug 31, 2015 at 12:59
  • 102
    what a useless component, who the heck come up with this specs?
    – boh
    Commented Jun 10, 2016 at 8:40
  • 2
    Display format now can be set to match the OS' locale in Firefox from the Settings panel, check my answer for details. Chrome should (or could) have this option added by now.
    – andreszs
    Commented Sep 29, 2021 at 14:53
191
+250

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!

7
  • but are any of those localizable? i.e. change the month names to non-english. And do they work on desktop and mobile?
    – Sam Hasler
    Commented Aug 24, 2015 at 13:50
  • Sure, they're localizable. You could take advantage of the system's locale (i.e: is.gd/QSkwAY) or provide your i18n files inside the webcomponent (i.e: is.gd/Ru9U82). As for mobile browsers, they’re supported using polyfills, although not 100% (yet)… Check the browsers/versions link I posted. Again, this is bleeding edge. If you're forward-looking, it's a great solution.
    – sdude
    Commented Aug 24, 2015 at 18:27
  • Sorry, I hadn't seen your latest comment. This: jcrowther.io/2015/05/11/i18n-and-web-components looks quite useful and should be included in the answer.
    – Sam Hasler
    Commented Aug 27, 2015 at 8:44
  • @SDude Looks like the links you indicated you thought worth including are still not included.
    – Mark Amery
    Commented Jan 16, 2020 at 19:40
  • 64
    Although over 100 people apparently disagree, this answer doesn't seem to me like it adds anything useful. There's no rationale given for why web components (rather than any other way of creating a reusable widget for a webpage) should be solution of choice here, and at least the first component proposed is a bit rubbish (no calendar popup, some crazy behaviours if I typo a too-large number for e.g. the day). Also, at no point do you actually show how to set a custom date format with any of your suggested components, meaning that ultimately this doesn't answer the question that was asked.
    – Mark Amery
    Commented Jan 16, 2020 at 19:48
115

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/

Note: if you want to customize the display format, only change the data-date-format attribute on the input element. Do not change the YYYY-MM-DD format string passed to moment.

$("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.

9
  • 1
    Nice example but it doesn't quite work on iOS (10.0). While the functionality is there, the styling is off.
    – Nic Nilov
    Commented Sep 29, 2016 at 15:07
  • 5
    Doesn't work neither in Safari, Edge, Opera - which make it unusable
    – MaxZoom
    Commented Apr 26, 2018 at 17:13
  • 14
    Broken in Firefox Commented Oct 3, 2018 at 15:53
  • Good if modern browsers like chrome, that supported the CSS content atrr sintax
    – Miguel
    Commented Nov 13, 2018 at 11:26
  • Thanks for pointing the ability to display attribute content in before/after pseudo-elements. I've learned something new today:)
    – Maxím G.
    Commented Sep 27, 2019 at 9:51
61

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.

3
  • 3
    Does the value attribute match the wire format, or what is displayed to the user?
    – Flimm
    Commented Aug 17, 2017 at 15:46
  • 5
    @Flimm the value attribute always matches the wire format. Commented Mar 2, 2018 at 20:52
  • 6
    The W3C adds a new control once per decade, but they fail to consider different display locales... I'd really like to work there to get paid for doing nothing!!
    – andreszs
    Commented Sep 29, 2021 at 14:40
30

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">

3
  • 6
    Its not working in firefox browser. is there any way to handle date format by css that works in firefox?
    – Shoaib
    Commented Nov 14, 2020 at 13:32
  • Thanks @safi eddine- if somebody is doing custom style on this you can use - input[type="date"]::-webkit-datetime-edit-text to remove the "//" before the dd input[type="date"]::-webkit-datetime-edit-text { color: transparent; }
    – user13028588
    Commented May 31, 2021 at 18:08
  • Thank you! I found one more way to change from / to . (dot): input[type="date"] {position:relative;} input[type="date"]::-webkit-datetime-edit-text {background:#333; width:2px; height:2px; margin:0 1px 0 0; display:inline-block; overflow:hidden;} input[type="date"]::-webkit-datetime-edit-day-field {position:relative; left:-20px;} input[type="date"]::-webkit-datetime-edit-month-field {position:relative; left:20px;}
    – Webfeya
    Commented Sep 28, 2023 at 13:21
18

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.

3
  • 1
    local date format means our phone default date format or location date formate? Commented Oct 11, 2011 at 4:14
  • 2
    Depends on what mobile browser you're using. But I suspect it will be the phone's default. Commented Oct 11, 2011 at 13:00
  • 3
    "Local" format means based on geographic location, which is possibly the worst way to determine a date format. Would an American travelling to Europe expect their smart phone to start showing time in 24hr format and dates as yyyy-mm-dd or dd/mm/yyyy? Or vice versa for a European in the US?
    – RobG
    Commented May 19, 2016 at 0:06
13

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

12

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.

5
  • 26
    The DD-MM-YYYY format you mention is probably your local calendar format. It is not wise (and as far as I can see, impossible within the current HTML5 standards) to force a specific format on visitors of a website, because they might be used to a calendar format different from the one you force upon them. Commented Aug 22, 2012 at 8:49
  • 4
    You are referring to the presentation format, because if you try to read the input.val(), google chrome (v35) returns the date in format yyyy-mm-dd, whatever the presentation format is ;)
    – Tilt
    Commented Jun 27, 2014 at 15:31
  • 10
    @DavidWalschots if only the americans would realize how unwise it is to force the retarded m-d-y format on the rest of the world.
    – user275801
    Commented Sep 24, 2018 at 9:35
  • @user275801 While I agree that M-D-Y is an odd format. I've not seen Americans forcing it onto others. :-) Commented Sep 24, 2018 at 17:27
  • 5
    @DavidWalschots most software and operating systems I've seen requires you to "opt-out" of the american m-d-y format. In that sense, it is in fact "forced". In fact my linux has all the regional settings for Australia, but my browser (an american browser, if it can be called that) still takes it upon itself to display all dates in m-d-y format, and in this case I'm unable to "opt-out".
    – user275801
    Commented Oct 8, 2018 at 2:01
11

Browsers obtain the date-input format from user's system date format.

(Tested in supported browsers, Chrome, Edge & Firefox.)

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.

Changing system date format on windows: To change the system date format on windows 10 or above, go to Start --> Date &Time settings --> Date, time & regional formatting-->Change the regional format (attached image).

After changing the format you may need to refresh the page or sometime restart the browser. enter image description here

If above doesn't work, you can try below in chrome:

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: chrome settings relaunch 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=""/>

14
  • 8
    For me this does not work. My Windows settings have format d.m.Y, but browser displays m/d/Y.
    – Maris Mols
    Commented Dec 25, 2020 at 15:56
  • which browser it is, and what is the version?
    – Rahul R.
    Commented Dec 28, 2020 at 7:12
  • Im using Chrome
    – Maris Mols
    Commented Dec 29, 2020 at 9:01
  • This shouldn't be the case as per documentation, Just check the version and make sure its latest, if its latest, you can open a bug against chrome
    – Rahul R.
    Commented Dec 30, 2020 at 6:22
  • 1
    your need clear browser cache or use incognito window.
    – Sri
    Commented Apr 29, 2021 at 6:47
8

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:

enter image description here

7

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>

2
  • 5
    This doesn't answer the question and requires 2 libraries, neither of which are tagged or asked for. It also does not allow manual entry of the date.
    – RobG
    Commented May 19, 2016 at 0:16
  • it was not asked to be changed, only show format...you can do this as a preview, and use input with change events, to update the format anyway.
    – Miguel
    Commented May 19, 2016 at 2:30
6

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: https://ccollins.wordpress.com/2009/01/06/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.

1
  • +1 Great! using: LANG=ja_JP.UTF-8 chromium-browser did the trick for me. It also work with Vivaldi and I guess in other browsers too. Thanks!
    – lepe
    Commented Aug 17, 2015 at 1:10
4

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

2

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>

2

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?)

3
  • 2
    I've been unable to find this setting in Firefox v93.0. Is this for the regular Firefox, or is this perhaps part of the Developer Edition? Commented Oct 22, 2021 at 8:44
  • I have the regular Firefox 93.0, the option is at the Language section. Maye it will be hidden whenever the browser language matches the Windows region and language settings? I have english Windows and Firefox but the Windows locale is set to Spanish (Argentina).
    – andreszs
    Commented Oct 22, 2021 at 20:28
  • Seems somewhat of a strange (buggy?) settings feature. I have browser and Windows on English (UK) and my regional setting on Dutch. No option to pick Dutch formatting. If I change my browser to Dutch, then I get the setting to sync with Dutch formatting (while then it doesn't matter as the format is already correct). If I change it to Spanish, then the setting is removed again. Commented Oct 23, 2021 at 8:46
2

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.

1

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:

  1. it splits the date which i get as dd/mm/yyyy (using split()) on basis of "/" and makes an array,
  2. it then reverse the array (using reverse()) since the date input supports the reverse of what i get.
  3. 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.

1
  • 2
    This doesn't address the question asked; you're parsing a custom format here, not changing the format that the <input> uses to show the value.
    – Mark Amery
    Commented Jan 16, 2020 at 20:53
1

Thanks to @safi eddine and @Hezbullah Shah

img1

img2

img3

Img4

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
1

Not really no.

Hackable but very slim & customizable solution would be to:

  1. Hide date input (CSS visibility: hidden) (still shows calendar popup tho)
  2. Put a text input on top of it
  3. On text input click, use JS to get date input element & call .showPicker()
  4. store date picker value elsewhere
  5. 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>
0

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>

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Ethan
    Commented Jul 11, 2022 at 2:01
0

This is a simple compact solution (workaround), without any libraries.

Use two inputs. The true/actual input (which is hidden) and the facade (which is actually shown, but does not have a "name" attribute, hence fake).

<div>
    <input name="date" id="actualDate" type="date" hidden onchange="dateFacade.value=datefacade(this.value)">     
    <input id="dateFacade" type="text" class="form-control" onclick="actualDate.showPicker()">       
</div>

<script>
    let datefacade = (inputDate) => (new Date(inputDate)).toLocaleDateString('en-UK',{dateStyle: 'full'});
</script>

How it works:

When you click on the facade, the date picker of the actual input one is shown. When the real one changes (because you selected a date on the date picker), the facade input changes.

Of course, use your own datefacade function.

(Warning: It does not work in Codepen (due to a Codepen restriction). Copy the code to an actual HTML file, and it should work fine.)

0

Just for ISO format:

<input type="date" data-date="" data-date-format="YYYY-MM-DD" value="2023-12-20">

Example jsfiddle

1
  • This code snippet is not the same as the one mentioned in jsfiddle, this is using moment library in JS Commented Jun 11 at 6:58
-1

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">&#9660;</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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.