JavaScript Temporal API Cheatsheet

What is the Temporal API?

The Temporal API is a JavaScript Stage 3 proposal which will make it much easier to manipulate dates than using the existing Date methods. You can try it now (using polyfill shown below) however, as it is still experimental, it is not recommended for production use.

Polyfill

The temporal API is not fully integrated into JavaScript so you need to install and import a polyfill package to use it:

Terminal:

pnpm install @js-temporal/polyfill

JavaScript or TypeScript source file:

import { Temporal } from '@js-temporal/polyfill';

Methods

add

Convenient for adding on an arbitrary time period to a given time or date. You might use this to work out the time you want a session cookie to expire.

const result = Temporal.Now.plainDateTimeISO()
  .add({ hours: 2 })
  .toLocaleString('en-GB', { dateStyle: 'full', timeStyle: 'long' });
Now: Wednesday, 18 May 2022 at 06:34:58 UTC
Result: Wednesday, 18 May 2022 at 08:34:58 UTC

from

Create a new date based on year, month, day etc. values. You might use this to create a date from user form inputs, like a date of birth.

const result = Temporal.PlainDateTime.from({ year: 1997, month: 10, day: 1 }).toLocaleString(
  'en-GB',
  { dateStyle: 'full', timeStyle: 'long' },
);
Result: Wednesday, 1 October 1997 at 00:00:00 UTC

subtract

Convenient for taking off arbitrary time periods from given time or date. You might use this to filter the blog posts you want to show in a feed summary based on when they were created.

const result = Temporal.Now.plainDateTimeISO()
  .subtract({ months: 3 })
  .toLocaleString('en-GB', { dateStyle: 'full', timeStyle: 'long' });
Now: Wednesday, 18 May 2022 at 06:34:58 UTC
Result: Friday, 18 February 2022 at 06:34:58 UTC

with

You might want to set the date to a particular day of a month or a particular time on a given day. An example is where you want a user account to expire at midnight one month from today:

  • use add to shift the date to a month from today
  • use with to shift the time to a second before midnight
const result = Temporal.Now.plainDateTimeISO()
  .add({ months: 1 })
  .with({ hour: 23, minute: 59, second: 0 })
  .toLocaleString('en-GB', { dateStyle: 'full', timeStyle: 'long' });
Now: Wednesday, 18 May 2022 at 06:34:58 UTC
Result: Saturday, 18 June 2022 at 23:59:00 UTC

withTimeZone

You want to call a colleague in a remote location but first check the local timing in their time zone is socially acceptable:

const local = Temporal.Now.plainDateTimeISO().toZonedDateTime('Europe/London');
const remoteTimeZone = Temporal.TimeZone.from('America/Sao_Paulo');
const result = local.withTimeZone(remoteTimeZone).plainDateTimeISO().toLocaleString('en-GB', {
  dateStyle: 'full',
  timeStyle: 'long',
});
Now: Wednesday, 18 May 2022 at 06:34:58 BST
Result: Wednesday, 18 May 2022 at 02:34:58 GMT-3

Resources

Some useful links for extra colour: