Set the value of datetime-local input field from an Date object
Kevin Luo

Kevin Luo @kevinluo201

About: Hi, I'm developer from Taiwan but now living in Toronto. I always like simple things. My hobby is to make knowledge very simple and easy to understand.

Location:
Toronto, Canada
Joined:
Dec 1, 2019

Set the value of datetime-local input field from an Date object

Publish Date: Jun 11 '23
7 3

We can use datetime-local to let user enter a date-time string. Most browsers have already implemented a native UI for it. It should be the most ideal way to have date-time input.

<input 
  id="start-time" 
  type="datetime-local" 
  name="start_time"
>
Enter fullscreen mode Exit fullscreen mode

The input is always blank at the beginning. I wanted to give it the current time as its default value but it didn't work.

const currentTime = new Date()
document.getElementById('start-time').value = currentTime // does not work
Enter fullscreen mode Exit fullscreen mode

Because datetime-local only accepts a specific string value, YYYY-mm-ddTHH:MM

  • YYYY-mm-dd is the year-month-date
  • T is just the seperator of date and time
  • HH:MM is the hours and minutes

Therefore, instead of assigning a Date object directly, you have to convert it first into that form. You can use toISOString() because the it will convert the Date object to
YYYY-MM-DDTHH:mm:ss.sssZ and the first part is exactly the same format the datetime-local needs.

const currentTime = new Date()
document.getElementById('start-time').value = currentTime.toISOString().slice(0, 16);
Enter fullscreen mode Exit fullscreen mode

However, it has a problem that it will use the UTC time which is timezone +00:00. I guess not so many people live within that time zone compared to all populations on Earth. I think most developers want to convert that to the local time.

Unfortunately, I found it ridiculously difficult to do that because there's no suitable method for handling that. I think it's due to the fact that most languages have a method similar to strftime so we are used to using an existing method to do what we want. There are some methods like toLocaleString() which seems like we can convert Date into some specific format but none of the format fits our needs. It feels like a basic functionality so I don't want to use any other libraries, either.

Finally, with some help from chatGPT and looking up of MDN page of the Date library. I finally realize the best to do that is to compose the string by myself.

// getFullYear, getMonth, getDate, getHours, getMinutes all return values of local time.
const convertToDateTimeLocalString = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");

  return `${year}-${month}-${day}T${hours}:${minutes}`;
}
const currentTime = new Date()
document.getElementById('start-time').value = convertToDateTimeLocalString(currentTime)
Enter fullscreen mode Exit fullscreen mode

Reference

Comments 3 total

  • Michael Etokakpan
    Michael EtokakpanFeb 21, 2024

    Wow! This was really helpful

  • Pau Riba
    Pau RibaMay 4, 2024

    Thanks!!

  • meirlamdan
    meirlamdanMay 23, 2024

    Nice and useful article

    It is common to solve these problems to use an external library like day.js or something similar

Add comment