How to Format Javascript Date as yyyy-mm-dd?

javascript

There are different ways to format a Javascript Date object as yyyy-mm-dd. Here are some examples:

  1. Using the toISOString() method:
let today = new Date();
let formattedDate = today.toISOString().slice(0,10);
console.log(formattedDate); // output: "2021-09-23"
  1. Using template literals and the getMonth() and getDate() methods:
let today = new Date();
let year = today.getFullYear();
let month = today.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
let day = today.getDate();
formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // output: "2021-09-23"
  1. Using the Intl.DateTimeFormat object:
let today = new Date();
let formatter = new Intl.DateTimeFormat('en', {year: 'numeric', month: '2-digit', day: '2-digit'});
let parts = formatter.formatToParts(today);
formattedDate = `${parts[4].value}-${parts[2].value}-${parts[0].value}`;
console.log(formattedDate); // output: "2021-09-23"

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?