Successfully added
React
by Patrik
Formatting Dates for HTML datetime-local Inputs
To populate an <input type="datetime-local">
in React, you must convert your UTC string into a local time string formatted as "yyyy-MM-ddTHH:mm"
— the only format the input accepts.
Implementation:
function toDatetimeLocalValue(dateInput) {
const date = new Date(dateInput);
const pad = (n) => n.toString().padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
Use this function when binding input values in forms to ensure users see time in their own timezone.
react
datetime-local
form
date formatting
utc
Referenced in:
Comments