An Introduction to JavaScript Temporal API

An Introduction to JavaScript Temporal API – SitePoint

Skip to main content

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Whatever your opinion of JavaScript, everyone thinks date handling is a mess. The Date() object implementation was copied directly from Java in 1995. Java scrapped it two years later but it remained in JavaScript for backward compatibility.

These are the problems we face with Date():

  • it only supports UTC and the user’s local time
  • there’s no support for non-Gregorian calendars
  • daylight-saving behavior is unpredictable
  • parsing dates from strings is unreliable
  • the API is clunky
  • Date objects are mutable: a date will change as methods are applied

The most popular alternative used to be the moment.js date library. However, this has been placed in maintenance mode and should not really be used in new projects. They recommend a couple of alternatives, but each of these have their own pros and cons.

The Date() object can’t be removed from JavaScript, but a new Temporal option is at stage 2 in the TC39 standards approval process. The properties and methods discussed here are subject to change, but the API should arrive in browsers and runtimes some time in 2021.

Temporal Time

Temporal is a top-level static global object (like Math).

Its main objectives are:

  • a predictable cross-browser/runtime behavior
  • easier APIs for date and time computations
  • support for non-Gregorian calendars
  • support for all time zones, including daylight-saving arithmetic
  • parsing of strictly specified ISO-8601 strings
  • making all objects immutable

The API is comprehensive and may change, but you can look forward to the following key features at some point in the near future.

Current Date and Time

Temporal.now returns the current date/time, which can be passed to further methods to provide additional information. For example:


Temporal.now.instant();
Temporal.now.instant().epochSeconds;
Temporal.now.instant().epochMilliseconds; Temporal.now.timeZone(); Temporal.now.zonedDateTimeISO(); Temporal.now.zonedDateTimeISO('Europe/London');

Creating Instant Date/Times

The Temporal.Instant object represents a single point in time to the nearest nanosecond. It can be created from ISO 8601 formatted strings, or a number of seconds, milliseconds, or microseconds:

const t1 = Temporal.Instant.from('2021-03-30T01:45:00+01:00[Europe/Berlin]'), t2 = Temporal.Instant.from('2021-04-01T02:00+01:00'), t3 = Temporal.Instant.fromEpochSeconds(1.0e8), t4 = Temporal.Instant.fromEpochMilliseconds(1.0e10), t5 = Temporal.Instant.epochNanoseconds(1.0e12);

Creating Zone-aware Date/Times

The Temporal.ZonedDateTime object represents a timezone and calendar-aware date/time at the instant it occurred (or will occur) in a particular region. A variety of different constructors can be used:

new Temporal.ZonedDateTime( 1234567890000, Temporal.TimeZone.from('America/Los_Angeles'), Temporal.Calendar.from('iso8601') ); Temporal.ZonedDateTime.from('2025-12-07T03:24:30+02:00[Africa/Cairo]'); Temporal.Instant('2022-08-05T20:06:13+05:45').toZonedDateTime('+05:45'); Temporal.ZonedDateTime.from({ timeZone: 'America/New_York' year: 2025, month: 1, day: 7, hour: 9, minute: 30, second: 1, millisecond: 2, microsecond: 3, nanosecond: 4
});

Creating Plain Dates and Times

It’s not always necessary to use exact moments, so the Temporal API provides objects which are independent of time zones. These could be used for simpler events, such as a meeting at 2pm today.

All have similar constructors:

 new Temporal.PlainDateTime(2021, 5, 4, 13, 14, 15);
Temporal.PlainDateTime.from('2021-05-04T13:14:15'); new Temporal.PlainDate(2021, 5, 4);
Temporal.PlainDate.from('2021-05-04'); new Temporal.PlainTime(13, 14, 15);
Temporal.PlainTime.from('13:14:15'); new Temporal.PlainYearMonth(2021, 4);
Temporal.PlainYearMonth.from('2019-04'); new Temporal.PlainMonthDay(3, 14);
Temporal.PlainMonthDay.from('03-14');

All Temporal objects can return discrete values about a specific date/time. For example, using a ZonedDateTime:

const t1 = Temporal.ZonedDateTime.from('2025-12-07T03:24:30+02:00[Africa/Cairo]'); t1.year; t1.month; t1.day; t1.hour; t1.minute; t1.second; t1.millisecond; t1.microsecond; t1.nanosecond; 

Other useful properties include:

  • dayOfWeek (1 for Monday to 7 for Sunday)
  • dayOfYear (1 to 365 or 366)
  • weekOfYear (1 to 52, or sometimes 53)
  • daysInMonth (28, 29, 30, or 31)
  • daysInYear (365 or 366)
  • inLeapYear (true or false)

Comparing and Sorting Dates

All Temporal objects can be compared using a compare() function, which returns an integer. For example, to compare two ZonedDateTime objects:

 Temporal.ZonedDateTime.compare(t1, t2);

compare() can be used as an Array sort() function to arrange date/times into ascending chronological order (earliest to latest):

const t = [ '2022-01-01T00:00:00+00:00[Europe/London]', '2022-01-01T00:00:00+00:00[Africa/Cairo]', '2022-01-01T00:00:00+00:00[America/New_York]' ].map( d => Temporal.ZonedDateTime.from(d) ) .sort( Temporal.ZonedDateTime.compare );

Date Calculations

Several methods are provided to perform date calculations on any Temporal object. All return a new Temporal of the same type when passed a Temporal.Duration object, which defines a period in years, months, days, hours, and so on.

const t1 = Temporal.ZonedDateTime.from('2022-01-01T00:00:00+00:00[Europe/London]'); t1.add({ hours: 8, minutes: 30 }); t1.subtract({ days: 5 }); t1.round({ smallestUnit: 'month' });

Note that Plain dates and times can wrap. For example, adding 24 hours to any PlainTime will return an object holding an identical value.

The until() and since() methods return a Temporal.Duration object describing the time until or since a specific date/time:


t1.until().months; t1.since().weeks;

Finally, the equals() method can determine whether two date/time values are equivalent:

const d1 = Temporal.PlainDate.from('2022-01-31'); d2 = Temporal.PlainDate.from('2021-01-31'); d1.equals(d2); 

Formatting Dates With the Internationalization API

While not part of the Temporal API, the JavaScript Intl (Internationalization) API provides a DateTimeFormat() constructor which can be used to format Temporal or Date objects:

const d = new Temporal.PlainDate(2021, 3, 14); new Intl.DateTimeFormat('en-US').format(d); new Intl.DateTimeFormat('en-GB').format(d); new Intl.DateTimeFormat('es-ES', { dateStyle: 'full' }).format(d);

About Time?

The Date() object has been a cause of developer frustration for a quarter of a century. While there’s no guarantee Temporal will become a standard feature quickly, the future for JavaScript dates looks a little brighter.

You can try out Temporal today, via an experimental polyfill, but don’t use it in production (yet)!

Further information:

Leave a Reply

Your email address will not be published. Required fields are marked *