Today I Learned - Rocky Kev

TIL the new Temporal API

POSTED ON:

TAGS:

Temporal isn't in Javascript yet, as it's still a TC39 proposal. via https://tc39.es/proposal-temporal/docs/

Calendars

The calendars supported by Temporal are based on the standard Unicode Unicode Common Locale Data Repository (CLDR) – among others:

iso8601 is used by most western countries and gets extra support in Temporal, via methods such as Temporal.Now.zonedDateTimeISO() (which returns the current date and wall-clock time in the system time zone and ISO-8601 calendar).

const cal = Temporal.Calendar.from("iso8601");
const date = cal.dateFromFields({ year: 1999, month: 12, day: 31 }, {});
date.monthsInYear; // => 12
date.daysInYear; // => 365

Two clocks

Temporal distinguishes two kinds of time. Given a global instant of time:

// Wall-clock time using PlainTime method
const time = Temporal.PlainTime.from({
hour: 19,
minute: 39,
second: 9,
millisecond: 68,
microsecond: 346,
nanosecond: 205,
}); // => 19:39:09.068346205

time.second; // => 9
time.toString(); // => '19:39:09.068346205'

// Exact Time using Instant method
const instant = Temporal.Instant.from("1969-07-20T20:17Z");
instant.toString(); // => '1969-07-20T20:17:00Z'
instant.epochMilliseconds; // => -14182980000

Duration

A duration represents a length of time – for example, 3 hours and 45 minutes.

It's to measure differences between two Temporal values.

const pdStart = Temporal.PlainDate.from("2022-03-08");

const pd1 = pdStart.add(
Temporal.Duration.from({ years: 5, months: 2, days: 1 })
);

// assert.equal(pd1.toString(), '2027-05-09');

const pd2 = pdStart.add({ years: 5, months: 2, days: 1 });

// assert.equal(pd2.toString(), '2027-05-09');

const pd3 = pdStart.add("P5Y2M1D");

// assert.equal(pd3.toString(), "2027-05-09");

via Temporal: getting started with JavaScript’s new date time API


Related TILs

Tagged:

TIL the new Temporal API

Temporal is a TC39 proposal for a non-sucky date time API

TIL about the End of Time! (for Unix)

On January 19th, 2038 at precisely 03:14:07 UTC, instead of the clock going to 03:14:08 UTC, it will overflow and go to 20:45:52 UTC of December 13th, 1901.

TIL about the End of Time! (for Unix)

On January 19th, 2038 at precisely 03:14:07 UTC, instead of the clock going to 03:14:08 UTC, it will overflow and go to 20:45:52 UTC of December 13th, 1901.