A Guide to Date and Time Formatting in JavaScript
Tags: intl, javascript, a11y, webdev
Published: 2023-08-22 21:54:13

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:


```ts
const dateFormatter = new Intl.DateTimeFormat('en-GB');
```
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:

```ts
const now = new Date();
const formattedDate = dateFormatter.format(now);
// United Kingdom
console.log(formattedDate); // 22/08/2023
```

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

```ts
// United States
console.log(new Intl.DateTimeFormat('en-US').format(now)); // 8/22/2023
```

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
```ts
// Arabic
console.log(new Intl.DateTimeFormat('ar').format(now)); // ٢٢/٨/٢٠٢٣
```

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.
```ts
new Intl.DateTimeFormat(locale, options)
```

### `locale`

This is the first argument, and these are the various locale that are supported, examples could be found [here](https://meta.wikimedia.org/wiki/Template:List_of_language_names_ordered_by_code)

```ts
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
```

### `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](https://www.iana.org/time-zones)
- 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCalendars#supported_calendar_types).
- 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat).


```ts
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
```

Setting time zones

```ts
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
```

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

```ts
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
```

## 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](https://formatjs.io/docs/polyfills/intl-datetimeformat/#usage) 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!