javascript
  1. javascript-date-format

JavaScript Date Format

The Date object in JavaScript provides various methods to format the date and time in a desired format. This page discusses JavaScript Date Format in detail.

Syntax

The syntax for formatting date and time using the Date object in JavaScript is as follows:

dateObject.toLocaleDateString([locales[, options]])

Here, dateObject is a variable representing a Date object, locales is an optional parameter specifying a locale or an array of locales, and options is an optional object specifying various formatting options.

Example

const date = new Date('2022-01-01T00:00:00')
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' }
console.log(date.toLocaleDateString('en-US', options)); // Output: Saturday, January 1, 2022, 12:00:00 AM EST

Explanation

In the above example, we create a new Date object using the Date constructor with the date value set as 2022-01-01T00:00:00. We then create an options object that specifies the desired formatting options for the date string.

Finally, we call the toLocaleDateString method on the Date object with the options object and an optional locales parameter set to 'en-US' to format the date string in US English locale.

Use

We can use the toLocaleDateString method to format a Date object in a variety of formats using different formatting options. This can be useful when displaying date and time information in a user-friendly way on a web page or in an application.

Important Points

  • The toLocaleDateString method returns a string representing the date and time in the requested format.
  • The toLocaleDateString method can accept an optional locales parameter to specify a locale or an array of locales for formatting the string.
  • The toLocaleDateString method can accept an optional options object to specify various formatting options for the date and time string.

Summary

JavaScript provides an easy and flexible way to format date and time strings using the toLocaleDateString method. With the help of various formatting options, we can customize the date and time string to our desired format.

Published on: