Alwin John's Blog

A Better Way to Handle Time in JavaScript (Temporal API)

Understanding the Temporal API – A Better Way to Handle Time in JavaScript

Aha, I love dates... I mean dates like this '2012-12-12' xD

I recently discovered that a new Date API called "Temporal" is available.

But I didn't think it would help in any manner, at least not yet, but it's a cool API, to be honest.

We are already familiar with the existing Date Object, right? It's old, weird, and confusing - but it works (mostly)(Sometimes O_O)


Why Dates Have Always Been a Mess

If you've used JavaScript long enough, you've probably seen this:

new Date('2025-10-20');

Depending on where you run that code - Chrome, Node, or your local timezone - it might give you different results.

That's because Date tries to do too much. It mixes time zones, UTC conversions, and local offsets all in one object.

Libraries like Moment.js and date-fns tried to fix that mess for years.

But now, we finally have something built into the language that does it right.

And I'll definitely use this when this is available everywhere...


So, What is the Temporal API?

The Temporal API is JavaScript's modern replacement for Date. It's designed to be precise, explicit, and time zone aware - without any of the old quirks.

Here's the best part:

Instead of one confusing Date object, Temporal gives you several focused ones.

Object Purpose
PlainDate Calendar date (no time)
PlainTime Time (no date)
PlainDateTime Date and time, no time zone
ZonedDateTime Full date/time with time zone
Instant Exact timestamp
Duration Difference between two Temporal objects

You choose what you actually need - no hidden conversions, no surprises.

Let's try it out

Example 1: (PlainDate)

const date = Temporal.PlainDate.from('2025-10-20');
console.log(date.year);  // 2025
console.log(date.month); // 10
console.log(date.day);   // 20

And it's actually consistent, everywhere.

Example 2: (PlainTime)

const start = Temporal.PlainTime.from('09:00');
const end = Temporal.PlainTime.from('17:30');
const duration = end.since(start);
console.log(duration.toString()); // PT8H30M

Example 3: (Timezone)

const meeting = Temporal.ZonedDateTime.from('2025-10-20T09:00:00+05:30[Asia/Kolkata]');
const nyTime = meeting.withTimeZone('America/New_York');

console.log(nyTime.toString()); 
// 2025-10-19T23:30:00-04:00[America/New_York]

It's a cool thing to check out

Getting Started

If you’re on Node 20+, you can try it right now with:

node --harmony-temporal

Or you can use the polyfill: GitHub Repo


Further Reading