[html] How to set date format in HTML date input tag?

I am wondering whether it is possible to set the date format in the html <input type="date"></input> tag... Currently it is yyyy-mm-dd, while I need it in the dd-mm-yyyy format.

This question is related to html date input format

The answer is


Here is the solution:

  <input type="text" id="end_dt"/>

$(document).ready(function () {
    $("#end_dt").datepicker({ dateFormat: "MM/dd/yyyy" });
});

hopefully this will resolve the issue :)


I made a lot of research and I don't think one can force format of the <input type="date">. The browser select the local format, and depending on user settings, if the user's language is in English, the date will be displayed to the English format (mm/dd/yyyy).

In my opinion, the best solution is to use a plugin to control the display.

Jquery DatePicker seems a good option since you can force the localization, date format ...


Clean implementation with no dependencies. https://jsfiddle.net/h3hqydxa/1/

  <style type="text/css">
    .dateField {
      width: 150px;
      height: 32px;
      border: none;
      position: absolute;
      top: 32px;
      left: 32px;
      opacity: 0.5;
      font-size: 12px;
      font-weight: 300;
      font-family: Arial;
      opacity: 0;
    }

    .fakeDateField {
      width: 100px; /* less, so we don't intercept click on browser chrome for date picker. could also change this at runtime */
      height: 32px; /* same as above */
      border: none;
      position: absolute; /* position overtop the date field */
      top: 32px;
      left: 32px;
      display: visible;
      font-size: 12px; /* same as above */
      font-weight: 300; /* same as above */
      font-family: Arial; /* same as above */
      line-height: 32px; /* for vertical centering */
    }
  </style>

  <input class="dateField" id="dateField" type="date"></input>
  <div id="fakeDateField" class="fakeDateField"><em>(initial value)</em></div>

  <script>
    var dateField = document.getElementById("dateField");
    var fakeDateField = document.getElementById("fakeDateField");

    fakeDateField.addEventListener("click", function() {
      document.getElementById("dateField").focus();
    }, false);

    dateField.addEventListener("focus", function() {
      fakeDateField.style.opacity = 0;
      dateField.style.opacity = 1;
    });

    dateField.addEventListener("blur", function() {
      fakeDateField.style.opacity = 1;
      dateField.style.opacity = 0;
    });

    dateField.addEventListener("change", function() {
      // this method could be replaced by momentJS stuff
      if (dateField.value.length < 1) {
        return;
      }

      var date = new Date(dateField.value);
      var day = date.getUTCDate();
      var month = date.getUTCMonth() + 1; //zero-based month values
      fakeDateField.innerHTML = (month < 10 ? "0" : "") + month + " / " + day;
    });

  </script>

Why not use the html5 date control as it is, with other attributes that allows it work ok on browsers that support date type and still works on other browsers like firefox that is yet to support date type

<input type="date" name="input1" placeholder="YYYY-MM-DD" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" title="Enter a date in this formart YYYY-MM-DD"/>

We can change this yyyy-mm-dd format to dd-mm-yyyy in javascript by using split method.

let dateyear= "2020-03-18";
let arr = dateyear.split('-') //now we get array of these and we can made in any format as we want
let dateFormat = arr[2] + "-" + arr[1] + "-" + arr[0]  //In dd-mm-yyyy format

I found same question or related question on stackoverflow

Is there any way to change input type=“date” format?

I found one simple solution, You can not give particulate Format but you can customize Like this.

HTML Code:

    <body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt"  onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>

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


You don't.

Firstly, your question is ambiguous - do you mean the format in which it is displayed to the user, or the format in which it is transmitted to the web server?

If you mean the format in which it is displayed to the user, then this is down to the end-user interface, not anything you specify in the HTML. Usually, I would expect it to be based on the date format that it is set in the operating system locale settings. It makes no sense to try to override it with your own preferred format, as the format it displays in is (generally speaking) the correct one for the user's locale and the format that the user is used to writing/understanding dates in.

If you mean the format in which it's transmitted to the server, you're trying to fix the wrong problem. What you need to do is program the server-side code to accept dates in yyyy-mm-dd format.


short direct answer is no or not out of the box but i have come up with a method to use a text box and pure JS code 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.


I came up with a slightly different answer than anything above that I've read.

My solution uses a small bit of JavaScript and an html input.

The Date accepted by an input results in a String formatted as 'yyyy-mm-dd'. We can split it and place it properly as a new Date().

Here is basic HTML:

<form id="userForm">
    <input type="text" placeholder="1, 2, 3, 4, 5, 6" id="userNumbers" />
    <input type="date" id="userDate" />
    <input type="submit" value="Track" />
</form>

Here is basic JS:

let userDate = document.getElementById('userDate').value.split('-'),
    parsedDate = new Date((`${userDate[1]}-${userDate[2]}-${userDate[0]}`));

You can format the date any way you like. You can create a new Date() and grab all the info from there... or simply use 'userDate[]' to build your string.

Keep in mind, some ways that a date is entered into 'new Date()' produces an unexpected result. (ie - one day behind)


<html>

    <body>
        <p id="result">result</p>Enter some text: <input type="date" name="txt" id="value" onchange="myFunction(value)">
        <button onclick="f()">submit</button>
        <script>
            var a;

            function myFunction(val){
                a = val.split("-").reverse().join("-");
                document.getElementById("value").type = "text";
                document.getElementById("value").value = a;
            }

            function f(){
                document.getElementById("result").innerHTML = a;
                var z = a.split("-").reverse().join("-");
                document.getElementById("value").type = "date";
                document.getElementById("value").value = z;
            }

        </script>
    </body>

</html>

The format of the date value is 'YYYY-MM-DD'. See the following example

<form>
<input value="2015-11-30" name='birthdate' type='date' class="form-control" placeholder="Date de naissance"/>
</form>

All you need is to format the date in php, asp, ruby or whatever to have that format.


$('input[type="date"]').change(function(){
   alert(this.value.split("-").reverse().join("-")); 
});

If you're using jQuery, here's a nice simple method

$("#dateField").val(new Date().toISOString().substring(0, 10));

Or there's the old traditional way:

document.getElementById("dateField").value = new Date().toISOString().substring(0, 10)

I don't know this for sure, but I think this is supposed to be handled by the browser based on the user's date/time settings. Try setting your computer to display dates in that format.


For Formatting in mm-dd-yyyy

aa=date.split("-")

date=aa[1]+'-'+aa[2]+'-'+aa[0]


I think so, in HTML there is no syntax for DD-MM-YYYY format. Refer this page http://www.java2s.com/Code/SQLServer/Date-Timezone/FormatdateMmmddyyyyhhmmdp.htm. Somewhat it will help you. Else use javascript date picker.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?