Horje
JavaScript's Latest Feature: Temporal API

JavaScript, the language of the World Wide Web is still not standing still and is developing in terms of demand from developers. Another relatively recent and shiny gem of JavaScript is the Temporal API. This new thing is intended to be a solution that will replace a not-very-powerful and rather confusing Date object, which is currently used in JavaScript applications to work with dates and times.

What is Temporal API?

This is a new built-in module in JavaScript that provides a temporal approach for the manipulation of date and time. It is aimed to be more reliable, consistent and easier to use than the classical Date object. It is important to note that the new Temporal API comes with types for entrée of dates, times, duration and much more with numerous ways to alter them.

Why Temporal API?

The Date object native to JavaScript has long been targeted for various shortcomings and failures on the part of the design. It is a volatile type that results in the manifestation of a lot of side effects, and it has never been as accurate and versatile as required in the contemporary world. These problems are solved by the Temporal API because it consists of a set of more precise and non-mutable objects for working with date and time.

Key Features of Temporal API

  • Immutability: Temporal objects are administered as unchangeable, and therefore once a temporal object has been formed its values cannot be altered.
  • Precision: The Temporal API has support for time values with nanosecond precision and therefore can be used for high precision.
  • Comprehensive Types: These are some of the types that are available in the API; Temporal.PlainDate, Temporal.PlainTime, Temporal.PlainDateTime, Temporal.Instant, Temporal.Duration, and more. This is due to the fact that each type is appropriate to be used under certain conditions.
  • Time Zone and Calendar Support: Temporal is very strong specifically in handling time zones and calendars so that the date and time differences could be absolutely correct for different regions or cultures.
  • Human-Readable Syntax: This API aims at making the workings of the date and time easier and much easier to read through.

Initialize a NodeJS Project

Before you can install math.js, you need to have a NodeJS project. If you don’t have one, you can create it using the following command:

npm init -y
Screenshot-2024-07-24-165848

Output

Note: Add “type”: “module” in package.json file:

{
"name": "ttemporall",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@js-temporal/polyfill": "^0.4.4"
}
}

Steps to Setup Temporal API

But before using Temporal in your JavaScript projects, for compatibility and correct implementation, there are some steps that you need to go through. Here’s a detailed guide to get you started, Here’s a detailed guide to get you started:

Step 1: Ensure Browser Compatibility

The Temporal API remains just a TC39 proposal and might not be natively supported in all browsers. If you want to have Temporal in places where it is currently not natively supported a polyfill will be needed.

Step 2: Get the Temporal polyfill

Temporal API can be accessed via adding the Temporal API polyfill of your choice using the npm or yarn packages. This makes it possible for you to use Temporal even if the native support is missing, as you will see later in this document.

Using npm:

 npm install @js-temporal/polyfill

Using yarn:

 yarn add @js-temporal/polyfill

Example: Creating Temporal Objects

JavaScript
// script.js

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

// Example: Creating Temporal Objects
console.log("Creating Temporal Objects");
const plainDate = Temporal.PlainDate.from("2023-07-19");
console.log("PlainDate:", plainDate.toString());

const plainTime = Temporal.PlainTime.from("14:35:29");
console.log("PlainTime:", plainTime.toString());

const plainDateTime
    = Temporal.PlainDateTime.from("2023-07-19T14:35:29");
console.log("PlainDateTime:", plainDateTime.toString());

const instant
    = Temporal.Instant.from("2023-07-19T14:35:29Z");
console.log("Instant:", instant.toString());

const duration
    = Temporal.Duration.from({hours : 1, minutes : 30});
console.log("Duration:", duration.toString());

Output

Creating Temporal Objects
PlainDate: 2023-07-19
PlainTime: 14:35:29
PlainDateTime: 2023-07-19T14:35:29
Instant: 2023-07-19T14:35:29Z
Duration: PT1H30M

Example: Performing Date Arithmetic

JavaScript
// script.js
import {Temporal} from "@js-temporal/polyfill";
// Example: Performing Date Arithmetic
console.log("\nPerforming Date Arithmetic");
const date1 = Temporal.PlainDate.from("2023-07-19");
const date2 = date1.add({days : 10});
console.log("Date after adding 10 days:", date2.toString());

const duration1 = Temporal.Duration.from({days : 5});
const date3 = date1.add(duration1);
console.log("Date after adding 5 days duration:",
            date3.toString());

const date4 = date1.subtract({months : 1});
console.log("Date after subtracting 1 month:",
            date4.toString());

Output

Performing Date Arithmetic
Date after adding 10 days: 2023-07-29
Date after adding 5 days duration: 2023-07-24
Date after subtracting 1 month: 2023-06-19

Example: Working with Time Zones

JavaScript
// script.js
import {Temporal} from "@js-temporal/polyfill";

// Example: Working with Time Zones
console.log("\nWorking with Time Zones");
const zonedDateTime = Temporal.ZonedDateTime.from(
    "2023-07-19T14:35:29+01:00[Europe/London]");
console.log("ZonedDateTime:", zonedDateTime.toString());

const newYorkZonedDateTime
    = zonedDateTime.withTimeZone("America/New_York");
console.log("New York ZonedDateTime:",
            newYorkZonedDateTime.toString());

const tokyoZonedDateTime
    = zonedDateTime.withTimeZone("Asia/Tokyo");
console.log("Tokyo ZonedDateTime:",
            tokyoZonedDateTime.toString());

Output

Working with Time Zones
ZonedDateTime: 2023-07-19T14:35:29+01:00[Europe/London]
New York ZonedDateTime: 2023-07-19T09:35:29-04:00[America/New_York]
Tokyo ZonedDateTime: 2023-07-19T22:35:29+09:00[Asia/Tokyo]

Example: Formatting Temporal Objects

JavaScript
// script.js
import { Temporal } from "@js-temporal/polyfill";

// Example: Formatting Temporal Objects
console.log("\nFormatting Temporal Objects");
const plainDateTime = Temporal.PlainDateTime.from("2023-07-20T14:35:14");
const zonedDateTime = Temporal.ZonedDateTime.from(
    "2023-07-19T14:35:29+01:00[Europe/London]");
console.log("PlainDateTime toString:", plainDateTime.toString()); 
console.log("PlainDateTime toLocaleString:", plainDateTime.toLocaleString()); 

console.log("ZonedDateTime toString:", zonedDateTime.toString());
console.log("ZonedDateTime toLocaleString:", zonedDateTime.toLocaleString()); 

Output

Formatting Temporal Objects
PlainDateTime toString: 2023-07-20T14:35:14
PlainDateTime toLocaleString: 20/7/2023, 2:35:14 pm
ZonedDateTime toString: 2023-07-19T14:35:29+01:00[Europe/London]
ZonedDateTime toLocaleString: 19/7/2023, 2:35:29 pm GMT+1

Example: Converting Date Object to Temporal Object

JavaScript
// script.js
import {Temporal} from "@js-temporal/polyfill";

// Example: Converting Date object to Temporal object
console.log("\nConverting Date object to Temporal object");
const dateObject = new Date("2023-07-19T14:35:29Z");
const temporalInstant
    = Temporal.Instant.from(dateObject.toISOString());
console.log("Converted Temporal.Instant from Date:",
            temporalInstant.toString());

const temporalPlainDate = Temporal.PlainDate.from(
    dateObject.toISOString().substring(0, 10));
console.log("Converted Temporal.PlainDate from Date:",
            temporalPlainDate.toString());

Output

Converting Date object to Temporal object
Converted Temporal.Instant from Date: 2023-07-19T14:35:29Z
Converted Temporal.PlainDate from Date: 2023-07-19

Example: Using Temporal.Duration for Date Arithmetic

JavaScript
// script.js
import {Temporal} from "@js-temporal/polyfill";

// Example: Using Temporal.Duration for Date Arithmetic
console.log(
    "\nUsing Temporal.Duration for Date Arithmetic");
const plainDateTime = Temporal.PlainDateTime.from("2023-07-20T14:35:14");
const temporalDuration = Temporal.Duration.from(
    {days : 1, hours : 2, minutes : 30});
const newDate = plainDateTime.add(temporalDuration);
console.log("DateTime after adding duration:",
            newDate.toString()); 

Output

Using Temporal.Duration for Date Arithmetic
DateTime after adding duration: 2023-07-21T17:05:14

JavaScript’s Latest Feature: Temporal API – FAQs

What distinguishes Temporal API from the Date object?

The Temporal API is designed for improvement over the Date object and its problems and inconsistencies. Other characteristics that the public does not know vary in the following ways; they are immutable, have higher precision notably in terms of nanoseconds and are well equipped with time zone and calendar support.

Is Temporal API supported in all the browsers that are currently in use?

At the moment, Temporal API is a TC39 proposal which is the committee that evolves JavaScript. It still may not be available and fully implemented in some browsers. Polyfills or transpilers like Babel can be used to achieve this by the developers.

What is the method to change the already created Date object into Temporal object if required?

You can also easily convert a value of the type Date to a Temporal value by utilizing the from method.

const date = new Date();
const temporalDate = Temporal.PlainDate.from(date.toISOString());

Is it possible to format Temporal objects in various formats that is, date-time formats?

Indeed, Temporal objects have methods incorporated to them for formatting. You can use toString() or any other formatting invoked from the API that you prefer.

Is it possible to get all date-time operations from Temporal API?

Temporal API is the most general API and is appropriate for performing most of the date-time operations. But of course, it rarely hurts to sort out concrete examples for the prospect in question and determine whether it meets all the needs.




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript SyntaxError - Unexpected string JavaScript SyntaxError - Unexpected string
How to Create Custom Functions in math.js? How to Create Custom Functions in math.js?
How to Perform Matrix Operations using Math.js? How to Perform Matrix Operations using Math.js?
How to Solve Equations with Math.js? How to Solve Equations with Math.js?
How to Handle Units and Conversions in math.js? How to Handle Units and Conversions in math.js?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
19