The new Temporal API is coming to JavaScript and will make working with dates and times MUCH easier.
Hello Dev’s its me Md Taqui Imam, So let's explore the new javascript temporal Api and please don't forget to drop a "🔥❤️🦄🙌" and Follow me.
🤔 What is Temporal Api ?
This new JavaScript feature makes working with dates and times easier and more reliable than the old Date object. It offers various types for handling dates, times, and durations, with many options to modify them.
Here’s why it’s a complete upgrade 🛠️:
1️⃣ Immutable objects (no more accidental mutations!)
2️⃣ Built-in timezone support without external libraries
3️⃣ Intuitive API for date arithmetic
4️⃣ Clear distinction between wall-clock time and exact time
5️⃣ First-class duration objects for time spans.
📌 How to access Temporal Api ?
Currently Temporal API can be accessed via Temporal API polyfill its you choice of using 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.
With NPM:
npm install @js-temporal/polyfill
With YARN:
yarn add @js-temporal/polyfill
Now Let’s See Some Examples 🔥
The code example in the image shows how much cleaner date operations become with Temporal.
1. Adding Time to a Date:
This code adds 2 hours to the current date and time, then formats it as a string.
2. Comparing Dates:
This code compares the current date and time with December 31, 2022, returning -1, 0, or 1 depending on whether the first date is before, equal to, or after the second date.
3. Creating a Date from a String:
This code creates a date object from an ISO date string and formats it as a string.
4. Subtracting Time from a Date:
This code subtracts 3 months from the current date and time, then formats it as a string.
5. Calculating the Duration Between Two Dates:
Works out how long the period between two dates is. You might use this when signing a JWT to work out how many seconds from now your expiry date is.
This code calculates the number of seconds between the current date and time and December 25, 2025
That’s it
For more examples and code reference checkout 👉 Temporal API Cheatsheet:
Who else 😅 is excited to never write “new Date()” again?
okay, see you in my next blog, till then
Happy coding.