How to format date as string in the format “yyyy-MM-dd” in Javascript

Posted by:

|

On:

|

Here are two ways to format a date to the “yyyy-MM-dd” string in JavaScript:

1. Using toLocaleDateString:

This method is the simplest and most versatile way to format dates in JavaScript. It allows you to specify the desired format and optionally the locale and other options.

const date = new Date();
const formattedDate = date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' });
console.log(formattedDate); // Output: 2024-02-09

2. Using string manipulation:

This method offers more flexibility for custom formatting but requires manual adjustments for leading zeros and month-to-number conversion.

const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // Add leading zero for single-digit months
const day = String(date.getDate()).padStart(2, '0'); // Add leading zero for single-digit days
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // Output: 2024-02-09

Additional notes:

  • Both methods return the formatted date as a string.
  • The toLocaleDateString method is generally recommended for its simplicity and flexibility.
  • If you need to handle dates in different locales, specify the relevant locale code in the options object.

Posted by

in