Tempoal API
What is Temporal API?
Temporal API is a replacement for Date Objects. The DAte object included in javascript has several issues that make it hard or frustrating to use. Temporal API simplifies and makes using date objects easy. Some of the issues with traditional date objects included only having support for the Gregorian calendar, only being able to use the user's time zone, and having the date object being mutable. Tempoal fixes these issues while making the implementation simple and straightforward.
Setting up Temporal API
First you need to install the Tempoal package with
npm install @js-temporal/polyfill
Second, you need to import Temporal to the project you are working on using this line of code
<script src="temporal.js" type="module"></script>
Temporal API Methods
Temporal.Now has serveral methods that allow the user to access and use their current date, time, and timezone. The following code examples show the methods and the and how to implement them.
Temporal.Now.zonedDateTime() // => 2023-04-03T7:05:25.014950013-6:00[American/Chicago]
Temporal.zonedDateTime.from({
timeZone: 'America/Los_Angeles',
year: 1995,
month: 12,
day: 7,
hour: 3,
minute: 24,
second: 30,
millisecond: 0,
microsecond: 3,
nanosecond: 500
}); // => 1995-12-07T03:24:30.0000035-08:00[America/Los_Angeles]
Temporal.PlainYearMonth.from({ year: 1995, month: 12 }); // => 1995-12
Temporal.PlainDate.from({ year: 1995, month: 12, day: 7 }); // => 1995-12-07
Temporal.PlainTime.from({ hour: 19, minute: 30, second: 25}); // => 19:30:25
The Temporal object also has add and subtract methods that return a new Temporal object. The until and since methods return Temporal.Duration objects formatted with years and days as the default. You can also specify the largest and smallest units you want to be used for the duration object.
const today = Temporal.PlainDate.from({year: 2023,month: 4,day: 20});
const nextMonth = today.add({ months: 1}) // => 2023-5-20
const lastYear = today.subtract({years: 1}) // => 2021-4-20
console.log(today.until(nextMonth)) // => P30D
console.log(today.until(nextMonth{ largestUnit: 'months'})) // => P1M0D
console.log(today.since(lastYear)) // => 1P0D
console.log(today.since(lastYear{ smallestUnit: 'days'})) // => P365D