According to the documentation, the value of a field datetime-local
must be a string containing the date and time in the format "yyyyyy-mm-ddThh:mm:ss.sss" (with the second and second fractions being optional).
That is, the month, day, hour and minute must be written with two digits (and with a zero on the left, if less than 10), and between date and time must have the letter "T" (this format is defined by ISO 8601 standard).
So just do it:
function getDateNow() {
let today = new Date();
let date = today.getFullYear() + '-' +
(today.getMonth() + 1).toString().padStart(2, '0') + '-' +
today.getDate().toString().padStart(2, '0');
let time = today.getHours().toString().padStart(2, '0') + ':' + today.getMinutes().toString().padStart(2, '0');
return date + 'T' + time;
}
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById('inputDateNow').value = getDateNow();
});
<input type="datetime-local" id="inputDateNow" readonly>
In case, I use toString()
to convert the numbers to string, and padStart
to fill in with zeros on the left, if necessary.
In your case, you were returning a Date
, but as already said, the value must be a string. A relatively common confusion has been made: as I have already said here, here and here, dates have no format.
A date is just a concept, an idea: it represents a specific point in the calendar.
The date of "1 January 1970", for example, represents this: the specific point of the calendar that corresponds to the first day of January 1970. To express this idea in text form, I can write it in different ways:
- 01/01/1970 (a common format in many countries, including Brazil)
- 1/1/1970 (American format, reversing day and month)
- 1970-01-01 (the format ISO 8601)
- First of January 1970 (in good Portuguese)
- January 1st, 1970 (in English)
- 1970 年 1 月 1 日 (in Japanese)
- and many others...
Note that each of the above formats is different, but all represent the same date (the same numerical values of the day, month and year).
That said, the Date
Javascript represents the concept of a date (a point in the timeline), but it itself does not have a format. Strings, in turn, can represent a date in a specific format. And the value
of a input type="datetime-local"
receives a string containing the date in a specific format.