Categories
Featured Development Resources HTML/Javascript

JavaScript Date Formatting

There are many libraries to perform date formatting with JavaScript, unfortunately they can add a lot of unwanted overhead to your JS and in many cases aren’t needed.

Easy Javascript Date Formatting Methods

The toLocaleString() method returns the date with formatted to specific locale passed as an option with in the form language-country. This makes for very easy localization of dates.

d = new Date()
console.log(d.toLocaleString('en-US'))
// 12/8/2022, 12:34:03 AM

The toDate() String method returns the date in local format.

d = new Date()
console.log(d.toDateString())
// Thu Dec 08 2022

The toTimeString() method returns the time in a local format.

d = new Date()
console.log(d.toTimeString())
// 00:39:47 GMT-0800 (Pacific Standard Time)

The toISOString() format returns the date formatted in iso 8601.

d = new Date()
console.log(d.toISOString())
// 2022-12-08T08:39:47.183Z

There are also a couple of Timezone specific methods.

The toUTCString() or toGMTString() method returns the date in the GMT time zone.

d = new Date()
console.log(d.toUTCString())
// Thu, 08 Dec 2022 08:39:47 GMT

Custom Date Formatting

These methods will hopefully cover all your date needs, but if they don’t it is possible to write a custom date format using toLocaleString()

This is done by passing in a second parameter to toLocaleString() along with the country and language parameters covering formatting.

There are a vast number of formatting options available, here’s an example of how you can use them to come up with a custom date format.

console.log(d.toLocaleDateString("fr-FR", {
  month: "long",
  weekday: "short",
  day: "numeric",
  year: "numeric",
}))
// jeu. 8 décembre 2022

If you need custom date formatting my suggestion would be to use a library such as the popular Luxon library (Moment.js was the most popular library for this, but is now deprecated) this will allow you to format dates using a simple string.

Conclusion

As you can see for most common types of date formatting and date localization can be done with vanilla JavaScript.and fortunately JavaScript has a number of built in methods