JavaScript Format date as yyyy-mm-dd


You can format a JavaScript Date object as yyyy-mm-dd using the toISOString() method and the substring() method.

Here’s an example:

const date = new Date();
const isoDate = date.toISOString();
const formattedDate = isoDate.substring(0, 10);
console.log(formattedDate); // "2023-05-01"

In this example, we’re creating a new Date object with the current date and time. We’re then calling the toISOString() method on the date object to get an ISO 8601 string representation of the date and time.

The toISOString() method returns a string in the format of yyyy-mm-ddThh:mm:ss.sssZ. To format the date as yyyy-mm-dd, we’re using the substring() method to extract the first 10 characters of the ISO string representation.

This method will return the formatted date as a string. If you need to use it as a Date object again, you can create a new Date object from the formatted string as follows:

const formattedDate = "2023-05-01";
const date = new Date(formattedDate);
console.log(date); // Sun May 01 2023 00:00:00 GMT+0000 (Coordinated Universal Time)

In this example, we’re creating a new Date object from the formatted string using the Date constructor.