DEV Community

loading...

JavaScript format Date as YYYY-MM-DD

racztiborzoltan profile image Rácz Tibor Zoltán ・1 min read

A simple and awesome method:

yourDate.toISOString().split('T')[0]

But be careful! This result based on UTC date and time.

Discussion

pic
Editor guide
Collapse
patarapolw profile image
Pacharapol Withayasakpunt

To get locale date and time, use new Date().getTimezoneOffset() in minutes, so it becomes

function getYYYYMMDD(d0) {
    const d = new Date(d0)
    return new Date(d.getTime() - d.getTimezoneOffset() * 60 * 1000).toISOString().split('T')[0]
}
Collapse
mugilancodes profile image
Mugilan

I prefer this

const today = new Date().toISOString().slice(0, 10)
console.log(today) // 2021-01-16
Enter fullscreen mode Exit fullscreen mode
Collapse
megajjks profile image
Jayro_Salazar

It work, thanks dut