26

I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:

<html>
...
<input id='date' type='date'>
...
</html>

<script>
...
var myDate = new Date();
$("#date").val(myDate);
...

I have also tried passing the date object as a string

var myDate = new Date().toDateString();
$("#date").val(myDate);

When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.

Thanks.

MyTimeFinder
  • 1,787
  • 4
  • 23
  • 28
  • 3
    `var myDate = new Date();` not `var myDate = new.Date();`. BTW, good reading on this at http://updates.html5rocks.com/2012/08/Quick-FAQs-on-input-type-date-in-Google-Chrome – j08691 Jan 09 '13 at 19:59
  • This might be a duplicate of http://stackoverflow.com/questions/6982692/html5-input-type-date-default-value-to-today – Tuanderful Jan 09 '13 at 20:00
  • 1
    The value needs to be in `yyyy-mm-dd` format for it to work. I figured that out by looking at the value of the input field after picking a date from the picker. DEMO: http://jsfiddle.net/Ptrgy/ – gen_Eric Jan 09 '13 at 20:55

6 Answers6

58

It must be set in ISO-format.

(function () {
    var date = new Date().toISOString().substring(0, 10),
        field = document.querySelector('#date');
    field.value = date;
    console.log(field.value);

})()

http://jsfiddle.net/GZ46K/

Robin Drexler
  • 4,307
  • 3
  • 25
  • 28
  • 8
    except that toISOString will give you a UTC date which is most likely not what you want. – terrinecold Mar 27 '15 at 14:33
  • 2
    This is a BAD ANSWER because it will likely lead to very hard to track down bugs - because, as terrinecold noted, it will give you a UTC date. If your date is in a different timezone, it might RESULT IN A DIFFERENT DATE than the one you started with(in your local timezone). – martixy Aug 29 '18 at 05:43
  • @martixy: terrinecold already gave the exact same comment *three years ago* without being rude. – Robin Drexler Aug 30 '18 at 06:58
  • It isn't immediately obvious from his comment why you might not want that. I am not being rude, just extra explicit about the results. Truth != rudeness. – martixy Aug 30 '18 at 07:14
  • As terrinecold mentions, toISOString() is not what you want -- it will most likely convert the date/time you have fed into the Date object to the UTC/Zulu time. – gwelter Nov 15 '19 at 15:22
  • i hate those nested unnamed function blocks that javascript has turned into these days. So uncivilized. – Nikhil VJ Feb 17 '20 at 02:47
15

Why Not to Use toISOString()

The <input type='date'> field takes a value in ISO8601 format (reference), but you should not use the Date.prototype.toISOString() function for its value because, before outputting an ISO8601 string, it converts/represents the date/time to UTC standard time (read: changes the time zone) (reference). Unless you happen to be working in or want that time standard, you will introduce a bug where your date will sometimes, but not always, change.

Populate HTML5 Date Input from Date Object w/o Time Zone Change

The only reliable way to get a proper input value for <input type='date'> without messing with the time zone that I've seen is to manually use the date component getters. We pad each component according to the HTML date format specification (reference):

let d = new Date();
let datestring = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
document.getElementById('date').value = datestring;

/* Or if you want to use jQuery...
$('#date').val(datestring);
*/
<input id='date' type='date'>

Populate HTML5 Date & Time Fields from Date Object w/o Time Zone Change

This is beyond the scope of the original question, but for anyone wanting to populate both date & time HTML5 input fields from a Date object, here is what I came up with:

// Returns a 2-member array with date & time strings that can be provided to an
// HTML5 input form field of type date & time respectively. Format will be
// ['2020-12-15', '01:27:36'].
function getHTML5DateTimeStringsFromDate(d) {

  // Date string
  let ds = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');

  // Time string
  let ts = d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');

  // Return them in array
  return [ds, ts];
}

// Date object
let d = new Date();

// Get HTML5-ready value strings
let dstrings = getHTML5DateTimeStringsFromDate(d);

// Populate date & time field values
document.getElementById('date').value = dstrings[0]
document.getElementById('time').value = dstrings[1]

/* Or if you want to use jQuery...
$('#date').val(dstrings[0]);
$('#time').val(dstrings[1]);
*/
<input type='date' id='date'>
<input type='time' id='time' step="1">
idmadj
  • 2,565
  • 2
  • 19
  • 23
gwelter
  • 1,054
  • 11
  • 14
  • Great reply and still the best strategy in 2021 as far as I'm aware. For the sake of completeness, the year should be zero-padded too. According to the docs on HTML date strings, years are required to be 4 or more characters. This would be needed when working with years below 1000. I've updated the answer to reflect that. – idmadj Mar 15 '22 at 20:03
7

Thank you j08691. That link was the answer.

To others struggling like me, when they say input is "yyyy-mm-dd" the MEAN it!

You MUST have 4 digits for the year. You MUST have a dash and no spaces. You MUST have 2 digits for day and month.

In my example myDate.getMonth for January would only return "1" (actually it returns "0" because for some reason javascript counts months from 0-11). To get this right I had to do the following:

var myDate, day, month, year, date;
myDate = new Date();
day = myDate.getDate();
if (day <10)
  day = "0" + day;
month = myDate.getMonth() + 1;
if (month < 10)
  month = "0" + month;
year = myDate.getYear();
date = year + "-" + month + "-" + day;
$("#date").val(date);

I hope this helps others not waste hours like I did testing this before October or before the 10th of the month! LOL

MyTimeFinder
  • 1,787
  • 4
  • 23
  • 28
3

Here is an answer based on Robin Drexlers but in local time.

//Get the local date in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 10);

//Set the field value
var field = document.querySelector('#date');
field.value = datestr;

If it's a datetime field you're modifying (as opposed to just the date) don't forget to add the time T00:00, or change the substring to 16 characters for example:

//Get the local date and time in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 16);

//Set the field value
var field = document.querySelector('#datetime');
field.value = datestr;
Community
  • 1
  • 1
mattbell87
  • 565
  • 6
  • 9
2

This below code populates the local date . The accepted answer populates UTC date.

  var date = new Date();
  field = document.querySelector('#date-id');
  var day = date.getDate();
  if(day<10){ day="0"+day;}

  var month = date.getMonth()+1;
  if(month<10){ month="0"+month;}

  field.value = date.getFullYear()+"-"+month+"-"+day;
sanath_p
  • 2,198
  • 2
  • 26
  • 22
1

I don't have the reputation points to comment on another answer, so I'll just add a new answer. And since I'm adding an answer, I'll give more details than I would've in a comment.

There's an easier way to zero pad than all of the juggling that everyone is doing here.

var date = new Date();

var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day   = ('0' + date.getDate()).slice(-2);
var year  = date.getFullYear();

var htmlDate = year + '-' + month + '-' + day;

console.log("Date: " + htmlDate);

Today, the output would be

Date: 2020-01-07

The code is building a dynamic string by prepending a quoted zero, then taking the last 2 characters with slice(-2). This way, if the zero makes it 01, the last 2 are 01. If the zero makes it 011, then the last two are 11.

As for the month starting at zero silliness, you can also add 1 dynamically before prepending the zero and everything still works. You just have to do the math operation before turning it into a string.

As a side note, I've noticed that when you update a date field, you have to hide the field before setting the value and show it after setting. I don't do this often enough, so I have to re-struggle each time I need to deal with it. Hopefully this will help someone from the future.

waves to future people

Laura
  • 154
  • 2
  • 5