DEV Community

loading...

JavaScript format Date as YYYY-MM-DD

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 (3)

Collapse
patarapolw profile image
Pacharapol Withayasakpunt • Edited

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]
}
Enter fullscreen mode Exit fullscreen mode
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