spalonytoster
spalonytoster

Reputation: 441

How to convert JavaScript Date object to string that is compatible with datetime-local input?

Basically I have a Date object. How can convert it to a string compatile with datetime-local format yyyy-MM-ddThh:mm?

I tried Date.toISOString method, but it doesn't work as it appends .SSSZ at the end. Gives me the following output The specified value "2017-04-10T17:02:00.320Z" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS"..

Does anyone have any clean solution to this problem?

Upvotes: 11

Views: 19553

Answers (4)

Mehdi
Mehdi

Reputation: 408

use moment.js to format the date to the corresponding one:

moment(new Date()).format('YYYY-MM-DDTHH:mm')

but not: moment(date).format("YYYY-MM-DDTkk:mm") the previous answer is wrong !!
kk is between 1 - 24 (which is not compatible with the textfield DateTime local)

Upvotes: 9

Lino Rabolini
Lino Rabolini

Reputation: 243

I'm running into the same problem, but I didn't want to use moment or any other big lib just for a simple calculation.

I just used the ISO date but added the timezone offset, so the input doesn't go crazy when using the arrows to navigate the date values.

const offset = new Date().getTimezoneOffset() * 1000 * 60
const getLocalDate = value => {
    const offsetDate = new Date(value).valueOf() - offset
    const date = new Date(offsetDate).toISOString()
    return date.substring(0, 16)
}

basically it adds the timezone offset and converts that to an ISO date, but then we strip the timezone with the substring(0, 16)

this gives us the correct "timezoned ISO" date.

I'm giving it a try but so far it works okay. I wish this gets resolved natively, it is weird that it doesn't work out of the box.

Upvotes: 9

spalonytoster
spalonytoster

Reputation: 441

I used moment.js library to format the date accordingly. This line of code does the trick moment(date).format("YYYY-MM-DDTkk:mm").

Upvotes: 21

T.J. Crowder
T.J. Crowder

Reputation: 1074088

Either theDate.toISOString().substring(0, 16), or build the string yourself with the getFullYear, getUTCDate, getUTCMonth (remember it starts at 0), etc. methods. Or use a library to do it.

Upvotes: 12

Related Questions