Open In App

How To Format JavaScript Date as yyyy-mm-dd?

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We use JavaScript built-in help methods from the Date class that help us to create a formatted version of the current date in the form of yyyy-mm-dd.

These are the approaches used to format JavaScript date as yyyy-mm-dd.

1. Using the ISO String Method

  • Create the date object and then convert the same into an ISO-specified string.
  • After obtaining the ISO string, we can split it at the "T" character to separate the date part from the time part. We use the split method to achieve this.
  • Finally, we can log or return the formatted date string, which is now in the desired "yyyy-mm-dd" format.

Example: In this example, we will use the iso string method to format the JavaScript date as yyyy-mm-dd

JavaScript
const formatDateISO = (date) => {
    // Convert the date to ISO string
    const isoString = date.toISOString();
    // Split at the "T" character to get the date part
    const formattedDate = isoString.split("T")[0];
    return formattedDate;
};

// Example usage
const currentDate = new Date();
console.log(formatDateISO(currentDate)); // Output: yyyy-mm-dd


Output

2024-09-25

2. Using JavaScript Method

  • In this method, we will use the methods of JS to calculate year, month, and date.
  • Further for date and month, for a single digit number, we will use padstart, which would add 0 to the start of the number if it is a number with less than 2 digits.
  • Use a variable to combine all of these variables and print the formatted date.

Example: In this example, we will use the javascript method to format the JavaScript date as yyyy-mm-dd

JavaScript
const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
};

// Example usage
const currentDate = new Date();
console.log(formatDate(currentDate));


Output

2024-09-25

Next Article
Article Tags :

Similar Reads