How to get a date in YYYY-MM-DD format with JavaScript?

Sometimes, we want to get a date in YYYY-MM-DD format.

In this article, we’ll look at how to get a date in YYYY-MM-DD format.

How to get a date in YYYY-MM-DD format with JavaScript?

To get a date in YYYY-MM-DD format, we can use the date toISOString method.

For instance, we write:

const d = new Date(2022, 2, 2)
const [date] = d.toISOString().split('T')
console.log(date)

to create a new date with the Date constructor.

Then we call toISOString on the date instance to return a date time string.

Next, we split the string with split called with 'T' to split the date time string into the date and time parts.

Finally, we get the date part with destructuring.

Therefore, date is "2022-03-02".

Conclusion

To get a date in YYYY-MM-DD format, we can use the date toISOString method.