JavaScript Date Formatting: Two Methods

In JavaScript, there are various ways to format dates.

Option 1: Utilize the toLocaleDateString() method.

var date = new Date();
var formattedDate = date.toLocaleDateString();
console.log(formattedDate);

The method will return a formatted date string based on the language and formatting options of the current region. For example, in the United States region, the returned format may be “6/12/2022”.

Option 2: Utilize the Intl.DateTimeFormat object.

var date = new Date();
var options = { year: 'numeric', month: 'long', day: 'numeric' };
var formatter = new Intl.DateTimeFormat('en-US', options);
var formattedDate = formatter.format(date);
console.log(formattedDate);

This method utilizes the Intl.DateTimeFormat object to format dates. The format of the date can be customized by passing different options. In the example above, the options formatted the date as “June 12, 2022”.

Both methods can customize the date formatting according to your needs.

bannerAds