TIL the new Temporal API
POSTED ON:
TAGS: datetime javascript proposal
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:
- buddhist: Thai Buddhist calendar
- chinese: Traditional Chinese calendar
- coptic: Coptic calendar
- dangi: Traditional Korean calendar
- ethiopic: Ethiopic calendar, Amete Mihret (epoch approx, 8 C.E.)
- gregory: Gregorian calendar
- hebrew: Traditional Hebrew calendar
- indian: Indian calendar
- islamic: Islamic calendar
- iso8601: ISO calendar (Gregorian calendar using the ISO-8601 calendar week rules)
- japanese: Japanese Imperial calendar
- persian: Persian calendar
- roc: Republic of China calendar
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 (also called local time or clock time) varies globally, depending on the time zone of a clock.
- Exact time (also called UTC time) is the same everywhere.
// 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: datetime