How to format JavaScript date into yyyy-mm-dd format?

To format a JavaScript date into "yyyy-mm-dd" format, you can use several methods. The most common approaches are using toISOString() with substring extraction or building the format manually.

Using toISOString() Method

The toISOString() method returns a date in ISO 8601 format. To get just the "yyyy-mm-dd" part, extract the first 10 characters:

<html>
  <head>
    <title>JavaScript Date Formatting</title>
  </head>
  <body>
    <script>
      var date = new Date();
      var formattedDate = date.toISOString().substring(0, 10);
      document.write("Full ISO: " + date.toISOString() + "<br>");
      document.write("yyyy-mm-dd: " + formattedDate);
    </script>
  </body>
</html>
Full ISO: 2024-01-15T08:13:47.648Z
yyyy-mm-dd: 2024-01-15

Manual Formatting Method

For more control, you can manually format the date using getFullYear(), getMonth(), and getDate():

<html>
  <head>
    <title>Manual Date Formatting</title>
  </head>
  <body>
    <script>
      var date = new Date();
      var year = date.getFullYear();
      var month = String(date.getMonth() + 1).padStart(2, '0');
      var day = String(date.getDate()).padStart(2, '0');
      var formatted = year + '-' + month + '-' + day;
      document.write("Manual format: " + formatted);
    </script>
  </body>
</html>
Manual format: 2024-01-15

Comparison

Method Pros Cons
toISOString().substring(0, 10) Simple, concise Always uses UTC time
Manual formatting Uses local time, more control Slightly more code

Key Points

  • toISOString() returns UTC time in ISO format
  • getMonth() returns 0-11, so add 1 for correct month
  • padStart() ensures two-digit formatting for month and day

Conclusion

Both methods work well for formatting dates as "yyyy-mm-dd". Use toISOString().substring(0, 10) for simplicity, or manual formatting when you need local time instead of UTC.

Updated on: 2026-03-15T23:18:59+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements