Getting year-month-date from JS dates

By

Learn how to get YYYY-MM-DD from a JavaScript Date in UTC, and how to build the same format from the local calendar date.

~~~

I had this need.

Basically I wanted today’s date in this format

2023-01-20T07:00:00+02:00

The requirement was T07:00:00+02:00 to always stay as-is (I didn’t want the time to change).

But I wanted today’s date to be the current date.

The toISOString() method of the Date object gives you a UTC timestamp:

'2023-01-10T07:35:37.826Z'

If you want the UTC date, slice its first 10 characters:

I was reaching for the getFullYear() and all those methods to get the data out of a date, but I figured I could just cut the string returned from toISOString() so I used this:

const date = new Date().toISOString().slice(0, 10)
const value = `${date}T07:00:00+02:00`

Be careful near midnight. The UTC date can be one day ahead of or behind the local date.

If you need the user’s local calendar date, build it from the local getters:

const now = new Date()
const year = now.getFullYear()
const month = String(now.getMonth() + 1).padStart(2, '0')
const day = String(now.getDate()).padStart(2, '0')

const date = `${year}-${month}-${day}`

Also remember that appending a fixed +02:00 offset does not account for daylight-saving changes. Use a time-zone-aware library or the Temporal API when the offset must represent a named time zone.

If you need a different output format, I built a free date formatting tool that generates the snippet for you.

~~~

Related posts about js: