How to set date format in HTML date input tag?
Asked Answered
E

13

115

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.

Ebracteate answered 8/8, 2011 at 6:47 Comment(3)
Isn't it a possible duplicate of Specifying the value output of of an HTML5 input type = date? ? I would say, this question here is better asked than that older one, but that older one has a pretty good answer.Thorianite
Possible duplicate of Is there any way to change input type="date" format?Nonattendance
My country settings are Dutch, and in Chrome it shows DD-MM-YYYY. Seems it depends on the windows settings of the client using the website.Tallis
F
12

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

Fattal answered 2/9, 2015 at 8:48 Comment(4)
Even better - use css to position a transparent date control over the regular inputKosher
Thanks for your reply,if you have any link or code for this, I need to updateFattal
This is a great option.Eudiometer
I think he is asking if it is possible with HTML (based on the question), not CSS nor Javascript.Sucrase
O
7

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)
Officialism answered 24/1, 2014 at 3:14 Comment(1)
It's fun that, today, the old way is the jQuery wayConcettaconcettina
S
2
$('input[type="date"]').change(function(){
   alert(this.value.split("-").reverse().join("-")); 
});
Speaks answered 31/7, 2017 at 7:20 Comment(1)
Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.Irrelevancy
S
1

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"/>
Shawana answered 6/7, 2016 at 16:23 Comment(3)
<pre><input type="text" 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"/></pre>Shawana
The requirement clearly was, I quote - "I need it in the dd-mm-yyyy format." How does this help?Bertsche
does not work with Firefox. This html shows an input with placeholder mm/dd/yyyy. My windows and my firefox are both set with Dutch as the first language. Windows regional setting shows short date: 30-11-2018.Belligerence
D
1

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

Discontented answered 30/8, 2018 at 9:35 Comment(0)
I
1

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)

Inaugurate answered 6/2, 2019 at 12:53 Comment(0)
A
1

For formatting in mm-dd-yyyy:

 aa = date.split("-")

 date = aa[1]+'-'+aa[2]+'-'+aa[0]
Adamec answered 1/3, 2019 at 8:9 Comment(0)
A
1

Here's one option. When the user is entering the date, the function reformats it. When they click the submit button, it populates the result div with the date in the format you're looking for.

<div id="result"></div>
<p>Enter some text:
<input type="date" name="txt" id="datefield" onchange="dateval(value)"></p>
<button onclick="postdate()">submit</button>

<script>
var a;

// Set the *value* of the input element to
// yyyy-mm-dd (text is unchanged)
function dateval(val) {
    var dv = document.getElementById("datefield");
    a = val.split("-").reverse().join("-");
    dv.type = "text";
    dv.value = a;
}

// Extract the yyyy-mm-dd value from the inpuut element,
// format it to dd-mm-yyyy and put it in the div
function postdate() {
    var dv = document.getElementById("datefield");
    var z = a.split("-").reverse().join("-");
    document.getElementById("result").innerHTML = a;
    dv.type = "date";
    dv.value = z;
}
</script>
Augustus answered 26/4, 2019 at 13:12 Comment(2)
When you post HTML code here, it's very important you format it as code. If you don't it's formatted as a part of the page, and your answer doesn't look like an answer. If you don't know how to format, there's a nice guide on it in the help centerCommercialism
This is a creative solution, but it isn't very bulletproof and has some quirky behavior with the value revertingCorpora
W
0

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.

Walls answered 8/8, 2011 at 7:37 Comment(0)
H
0

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.

Heinrich answered 21/9, 2018 at 19:49 Comment(0)
B
0

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
Bulgaria answered 20/8, 2020 at 9:1 Comment(0)
F
0

I've written simple method due to solve this issue with vanilla js. You can add it to your toolbox then use somewhere you need.

function SetDateToInput(date) {//gg-mm-yyy ===> yyyy-mm-dd
    let dateArray = date.split('-')
    if (dateArray[0].length == 1) dateArray[0] = "0" + dateArray[0]
    var newDate = `${dateArray[2]}-${dateArray[1]}-${dateArray[0]}`
    console.log(date,newDate)
    return newDate 
}

Note that if the lenght of the day less than 10, you should prepend it with "0" with it like third line. Otherwise input wont be able to show the date you want properly.

Using :

<script src="source"></script>//add your toolbox file here
document.getElementById("startEdit").value = SetDateToInput(data.startDate)
Flection answered 26/4 at 10:58 Comment(0)
H
-4

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.

Haldan answered 9/3, 2015 at 20:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.