How to Format Date to YYYYMMDD in Javascript


To get a string in YYYYMMDD format from a JavaScript Date object, you can use the getFullYear(), getMonth(), and getDate() methods to extract the year, month, and day components, respectively. You can then concatenate these components into a string in the desired format.

Here’s an example:

const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const formattedDate = `${year}${month.toString().padStart(2, '0')}${day.toString().padStart(2, '0')}`;
console.log(formattedDate); // e.g. "20230501"

In this example, we’re creating a new Date object with the current date and time. We’re then calling the getFullYear(), getMonth(), and getDate() methods on the date object to extract the year, month, and day components, respectively.

Note that the getMonth() method returns a zero-based index for the month (0 for January, 1 for February, etc.), so we’re adding 1 to the result to get the month as a number between 1 and 12.

We’re then using the toString() method to convert the year, month, and day components to strings, and the padStart() method to ensure that the month and day components have two digits (e.g., “01” instead of “1”).

Finally, we’re concatenating the year, month, and day components into a string in the format YYYYMMDD.