Formatting Dates for Input Elements
You'll learn how to convert JavaScript dates to and from the ISO 8601 format that HTML date inputs require.
The Browser's Strict Requirement
HTML's <input type="date">, <input type="time">, and <input type="datetime-local"> elements are wonderfully convenient—but they're picky about format. They only accept values in ISO 8601 format, which looks like "YYYY-MM-DD" for dates, "HH:mm" for times, and "YYYY-MM-DDTHH:mm" for datetime-local.
If you try to set an input's value using a Date object directly or a formatted string like "12/25/2024", the browser will silently ignore it. Your input will appear empty.
Converting Date Objects to Input-Compatible Strings
To populate a date input, convert your Date object to the correct ISO format:
const userBirthday = new Date(1990, 5, 15); // June 15, 1990
// For <input type="date">
const dateString = userBirthday.toISOString().split('T')[0];
// Result: "1990-06-15"
document.querySelector('#birthday').value = dateString;
For datetime-local, you need the date and time without the timezone:
const appointment = new Date(2024, 11, 25, 14, 30);
// Remove the 'Z' and milliseconds
const datetimeString = appointment.toISOString().slice(0, 16);
// Result: "2024-12-25T14:30"
document.querySelector('#appointment').value = datetimeString;
Reading Values Back from Inputs
When reading from date inputs, the browser gives you a string already in ISO format:
const inputValue = document.querySelector('#birthday').value;
// inputValue is "1990-06-15"
const parsedDate = new Date(inputValue);
// Now a proper Date object
Key Takeaway: HTML date/time inputs only accept ISO 8601 format strings (YYYY-MM-DD or YYYY-MM-DDTHH:mm), so use toISOString() with string manipulation to convert Date objects for display, and construct Date objects directly from input values when reading.