How to Format Javascript Date as yyyy-mm-dd?
There are different ways to format a Javascript Date object as yyyy-mm-dd. Here are some examples:
- Using the toISOString() method:
let today = new Date();
let formattedDate = today.toISOString().slice(0,10);
console.log(formattedDate); // output: "2021-09-23"
- 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"
- 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"