DEV Community

Ade Adeola
Ade Adeola

Posted on • Edited on

A Guide to Date and Time Formatting in JavaScript

Handling date and time in web applications is a common task, whether you're building a simple event scheduler or a full-fledged calendar app. JavaScript provides a powerful tool for dealing with date and time formatting through the Intl.DateTimeFormat object. In this blog post, we'll dive into the world of Intl.DateTimeFormat and explore how it can make your date and time handling more efficient and user-friendly.

Introduction to Intl.DateTimeFormat

The Intl.DateTimeFormat object is part of the Internationalization API, which was introduced in ECMAScript 2015 (ES6) to enable developers to perform various language-sensitive operations, including formatting dates and times according to different locales.

Using Intl.DateTimeFormat, you can:

  1. Format dates and times according to user preferences or specific locales.
  2. Display dates and times in a human-readable format.
  3. Customize the formatting of date and time components.

Basic Usage

Let's start with the basics of using Intl.DateTimeFormat. To create a new instance of this object, you simply pass one or more locale strings as arguments. The locale string defines the language and region to use for formatting. For example:

const dateFormatter = new Intl.DateTimeFormat('en-GB');
Enter fullscreen mode Exit fullscreen mode

In this example, we create a dateFormatter that formats dates and times according to the English (United Kingdom) locale.

To format a date, you call the format method of the dateFormatter and pass a Date object as an argument:

const now = new Date();
const formattedDate = dateFormatter.format(now);
// United Kingdom
console.log(formattedDate); // 22/08/2023
Enter fullscreen mode Exit fullscreen mode

The formattedDate variable now contains a human-readable string representing the current date and time in the 'en-US' locale.

Now, let's compare it to English (United States) locale

// United States
console.log(new Intl.DateTimeFormat('en-US').format(now)); // 8/22/2023
Enter fullscreen mode Exit fullscreen mode

As seen above, United States uses MM/DD/YYYY while United Kingdom uses DD/MM/YYYY and Intl.DateTimeFormat reflected these differences.

You can also do this with other languages

// Arabic
console.log(new Intl.DateTimeFormat('ar').format(now)); // ٢٢/٨/٢٠٢٣
Enter fullscreen mode Exit fullscreen mode

Now, you can customise the dates further

Customizing Date and Time Formatting

One of the most powerful features of Intl.DateTimeFormat is the ability to customize how dates and times are formatted. You can do this by providing an options object as the second argument when creating an instance of Intl.DateTimeFormat.

new Intl.DateTimeFormat(locale, options)
Enter fullscreen mode Exit fullscreen mode

locale

This is the first argument, and these are the various locale that are supported, examples could be found here

const spanishDateFormatter = new Intl.DateTimeFormat('es-ES', {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
});
const now = new Date();
const formattedDate = spanishDateFormatter.format(now);
console.log(formattedDate); // martes, 22 de agosto de 2023
Enter fullscreen mode Exit fullscreen mode

options

These are some of the notable options

  • weekday: How the days of the week will be written. Possible values are long (Wednesday), short (Wed) or narrow (W)
  • timeZone: Determines the current timezone to use to display the time e.g. America/Los_Angeles. Full list can be found on IANA time zone database
  • calendar: this is the type of calendar that will be used to render the date. Examples includes gregory, chinese, indian, islamic etc. You can find the full list MDN.
  • hour12: determine whether to use 12 hour time (2 pm) or 24-hour time (14:00). Default is false
  • year: How the year are displayed. This includes numeric (2022) or 2-digit (22)
  • month: How the month will be displayed. This includes numeric (8), 2-digit (08), long (August), short (Aug)and narrow (A)
  • day: Define how the day is displayed, with options for numeric and 2-digit.
  • hour: Customize the hour display, with options like 'numeric' and 2-digit'.
  • minute and second: Similarly, you can control the display of minutes and seconds.

There are about 18 options, you can find the full list on MDN.

const customDateFormatter = new Intl.DateTimeFormat("en-US", {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
});
const now = new Date();
const formattedDate = customDateFormatter.format(now);
console.log(formattedDate); // Tuesday, August 22, 2023
Enter fullscreen mode Exit fullscreen mode

Setting time zones

const nyDateFormatter = new Intl.DateTimeFormat("en-US", {
  timeZoneName: "short",
  timeZone: "America/Los_Angeles",
});
const formattedNYDate = nyDateFormatter.format(new Date());
console.log(formattedNYDate); // 8/22/2023, PDT
Enter fullscreen mode Exit fullscreen mode

Instead of providing individual options, you can collapse it into dateStyle and timeStyle. The possible values are full, long, medium and short

const formatter = new Intl.DateTimeFormat("en-GB", {
  dateStyle: "full",
  timeStyle: "full",
});
const now = new Date();
const formattedDate = formatter.format(now);
console.log(formattedDate); 
// Tuesday, 22 August 2023 at 22:30:29 British Summer Time


// long
// 22 August 2023 at 22:32:11 BST

// medium
// 22 Aug 2023, 22:32:58

// short
// 22/08/2023, 22:33
Enter fullscreen mode Exit fullscreen mode

Browser Support

Intl.DateTimeFormat is widely supported in modern web browsers, including Chrome, Firefox, Safari, and Edge. However, if you need to support older browsers, you may want to consider using a polyfill like formatJS to ensure consistent behaviour.

Conclusion

Intl.DateTimeFormat is a powerful tool for formatting dates and times in JavaScript applications. It allows you to create user-friendly and localized date displays while customizing the format to meet your specific needs. Whether you're building a simple date picker or a complex scheduling application, mastering Intl.DateTimeFormat will help you provide a better user experience and make your code more maintainable.

Thanks for reading, and if you have any suggestions or feedback, feel free to share them in the comments below!

Top comments (2)

Collapse
 
cwprogram profile image
Chris White

Thanks for writing up an article on internationalization! I wish it got discussed more sometimes! It's nice to see browsers providing this kind of interface (honestly I sometimes wish programming languages overall would as well). I highly recommend folks looking at having websites with international presence to take a read here. Don't forget that this is still one part of the overall internationalization package! Thanks for the great article and keep up the good work!

Collapse
 
diorla profile image
Ade Adeola

I'm happy to hear that you found the article informative, thank you. Internationalization is a crucial aspect of web development that is often overlooked. I think the Intl API is extensive, and each method deserves its own post to provide a complete picture. Cheers!