Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *