How to Format Dates in JavaScript

To format dates in JavaScript, you can use the “toLocaleDateString()” method of the Date object with the appropriate options.

Example

const date = new Date();

// Basic date format: MM/DD/YYYY
console.log(date.toLocaleDateString('en-US'));

// Date format with full month name: Month DD, YYYY
console.log(date.toLocaleDateString('en-US',
 {
   month: 'long', day: 'numeric', year: 'numeric'
 }));

// Date format with abbreviated month name: Mon DD, YYYY
console.log(date.toLocaleDateString('en-US',
 {
   month: 'short', day: 'numeric', year: 'numeric'
 }));

// Date format with custom separator: DD-MM-YYYY
console.log(date.toLocaleDateString('en-US',
   { day: '2-digit', month: '2-digit', year: 'numeric' }).replace(/\//g, '-')
);

Output

4/15/2023
April 15, 2023
Apr 15, 2023
04-15-2023

In these examples, a new Date object is created with the current date and time. The toLocaleDateString() method is called on the date object with a locale string and options object as arguments.

The locale string specifies the language and format for the date, and the options object specifies the format of the date.

Note that the options object can include various properties to format the date, such as day, month, year, weekday, hour, minute, second, and timeZoneName. The available options depend on the locale and browser being used.

Also, note that the toLocaleDateString() method returns a string, not a Date object. If you need to manipulate the date further, you should create a new Date object from the string using the Date() constructor, like this:

const dateString = date.toLocaleDateString('en-US',
 {
   month: 'short', day: 'numeric', year: 'numeric'
 });
const newDate = new Date(dateString);
console.log(newDate);

Output

4/15/2023
April 15, 2023
Apr 15, 2023
04-15-2023

In this code example, a new string dateString is created with a custom date format.

A new Date object newDate is created from the string using the Date() constructor. The newDate object is the same as the original date object but with a different format.

Leave a Comment