Why I think the Temporal API could be better

⚡ Prepare for a JavaScript interview with my new book →

Disclaimer: Don't take this rant too seriously. I totally understand Temporal API's importance (immutability, timezones, etc.). I just think, while we are here, we should make it actually useful and joyful for a developer to work with. Otherwise, we have libraries we can continue using.

The Temporal API is a new modern JavaScript API for date and time manipulation. Finally, we get the date/time API we deserve.

Here's one of the most common task we do as frontend developers: get some date from a REST server, and parse it into a date structure for further manipulation.

Here's how we do this now.

const dateStr = "'07-25-2022'"
const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
const [, month, day, year] = datePattern.exec(dateStr);
new Date(`${month}, ${day} ${year}`);

We have to manually parse the date using a regular expression (or any other way given the format is known) and create the Date object in the expected format. Not cool.

Now let's see how we do this with the Temporal API.

const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
const [, month, day, year] = datePattern.exec(dateStr);
new Temporal.ZonedDateTime.from({year, month, day, timeZone: Temporal.Now.timeZone()});

Huh, what? Doesn't look like an improvement to me.

Isn't that an obvious use case for a new date/time API?

Can't we just have nice toys as all the other kids have?

Python:

from datetime import datetime
datetime_object = datetime.strptime(date_str, '%m-%d-%Y')

Ruby:

require 'Date'
Date.strptime(date_str, "%m-%d-%Y")

Freaking Java:

SimpleDateFormat parser = new SimpleDateFormat("MM-dd-yyyy");
Date date = parser.parse(input);

All the above are parts of the language standard libraries and have been for decades! How is this fair?

And yes, some libraries do that, like momentjs (yes, I know, it's dead, kinda), date-fns, and others.

So I guess we will have to continue using those, or maybe next-generation libraries that would use Temporal API under the hood (here is a nice name for a library - "tau").

But if we are still to use 3rd-party libraries, how is this progress?

JavaScript Interview

JavaScript Interview

Prepare for a JavaScript interview and get your dream job.

LEARN MORE →