How to Format a Date in Javascript?

javascript

There are several ways to format a date in Javascript.

Use the toLocaleDateString function:

d = new Date();

console.log(d.toLocaleDateString("en-US")); 
// Outputs: 3/21/2023

console.log(d.toLocaleDateString("en-GB"));
// Outputs: 21/03/2023

Use toLocaleDateString function with options:

d = new Date();
options = {weekday: "long", day: "numeric", month: "long"};
console.log(d.toLocaleDateString("en-US", options));
// Outputs: Tuesday, March 21

For a full list of options refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options

Convert to ISO format using toISOString:

d = new Date();
console.log(d.toISOString());
// Outputs: 2023-03-21T10:37:21.539Z

Use getDate, getMonth and getFullYear:

d = new Date();
console.log(`${d.getDate()}-${d.getMonth()+1}-${d.getFullYear()}`);
// Outputs: 21-3-2023
// Note that the d.getMonth() indexing starts from 0 for January and ends at 11 for December

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?