How to Outsmart Time: Building Futuristic JavaScript Apps Using Temporal

Rate this content
Bookmark

For close to 25 years now, JavaScript developers have suffered at the hands of time: the Date object. We have tried all sorts of solutions from using popular libraries like Moment.js all the way to handling dates and times on the backend.

Now it's time to show "time" who is boss. With the Temporal API stable at Stage 3 and the polyfill ready for production use, let me show you how to harness the power of this delightful API in order to build powerful JavaScript applications that handle dates and times like we always wished we could. We shall also discuss the orthogonal features being worked on in the JavaScript Intl API and find out how these play along with each other and come together to form a comprehensive set of APIs that allow us to build state of the art date and time components in our applications.

25 min
11 Jun, 2021

Video Summary and Transcription

Temporal is a proposal in JavaScript that brings an ergonomic API for building futuristic JavaScript applications. It is now at stage 3 and implementers will start implementing it in different polyfills and browsers. Temporal includes classes for working with dates, times, time zones, calendars, and durations. The talk covers building an invoice calculator using Temporal, calculating durations between date times, creating and manipulating durations, understanding time relativity and rounding, and rewriting methods using Temporal. The speaker expresses gratitude to various contributors and provides a sandbox for exploration.

Available in Español

1. Introduction to Temporal

Short description:

Hello and welcome, everyone. Today we're going to talk about building futuristic JavaScript applications in Tempo. The Temporal proposal in JavaScript brings an ergonomic API with a special focus on common and complex use cases, including local calendar support. Temporal is now at stage 3.

Hello and welcome, everyone. I'm Ujwal. You can find me on the internet at whyzacooking. If you want to run into me on Twitter or GitHub, I'll have a terrible how terrible this talk is or want to talk about Tempo or TZ39 stuff. But today we're going to talk about building futuristic JavaScript applications in Tempo. So let's get into it.

Because I'm a self-obsessed person. Let's first talk about me. So, I have a compiler's hacker, Regalia. For those of you who don't know, it's a free software consultancy in Spain. We work on a bunch of cool things. We work on browsers, compilers, standards like the ones I'm going to talk to you about today and a bunch of cool Linux stuff. I am also a TC39 delegate, which is why I'm talking to you about these things. I am one of the editors of Ecma 402 and the champion of the proposal that we talked about today and also happen to be one of the co-collaborators of O.J.S.

Just to give you a little recap about the history of the whole temporal thing, what the buzz is all about, if you've used the date object in JavaScript ever to do any sort of date time handling, you would know that it is severely outdated. It has serious issues. It dates at least back to 1985, which is before I was born, so how is that for a metaphor? But it needs a lot of repairs, which means that if you're writing any serious date time handling application, you're probably using some popular third-party libraries. They're pretty popular these days in the JavaScript ecosystem. You're either using Moment or Luxon date functions, and, well, they fill a really important role in the JavaScript language, but there's still quite a few problems. There's still deficiencies, if you follow JavaScript drama not so long ago, Lighthouse, which is a tool that sort of gives you performance tips regarding a JavaScript code, started flagging applications that use Moment, asking them to use something that would use less bundle size. So that's, for example, one of the problems that cannot be solved in the user space, among a bunch of others that I'm going to talk to you about. But because of all these problems, we realized that something needed to be done on the programming language level itself. Thus I bring in Temporal.

So Temporal is a state-of-the-art, daytime handling proposal in JavaScript. It brings you not only to the present, but, as you will see in the next few slides, right into the future. One of the most interesting challenges that we had when designing the Temporal API was certainly about going to sort of conflicting things, right? There's JavaScript of proposals that you see that are more specifically geared towards advanced users, you know them when you see them. There's others that are more sort of geared towards beginners, they make your life easier, but not as much if you have been writing this language for like 10 years, and in Temporal, the beauty of the Temporal proposal is that it tries to pair an ergonomic API with a special focus on some of the most common use cases alongside some really powerful features that accommodate some of the most complex use cases, some of the use cases that have never been accommodated so far. Things including local calendar support, so including calendars like the Hebrew or Islamic calendar or custom time zones of calendars. These are truly features that have been so far overlooked. So temporal, the thing that I talked about just now, is now stage 3, which is great news.

2. Exploring Temporal

Short description:

Temporal is now at stage 3. Implementers will start implementing temporal in different polyfills and browsers. JavaScript developers can start using temporal in their applications, including production. Temporal includes classes such as instant, plain date time, plain time, plain date, and zone date. It also encompasses time zones, calendars, and durations. Instant represents absolute points in time, while plain types deal with world clock time and calendar dates. Zone date time combines an instant and a time zone.

Except we don't really know what that means. So just to sum it up real quick, in the interest of time, it means that all the tiny details have been discussed. You've been sitting around in our chairs for a long time and realized that we've basically exhausted everything that we could have done while sitting in our chairs. So the specification text has been approved, the committee is now satisfied with the general design, and now the idea is to start implementing and using temporal.

So for implementers like us, that means that we will start implementing things in different polyfills. We will start implementing temporal in different browsers, and for you amazing JavaScript developers, it means that you can start using temporal in your applications, including production. Just to give you a quick idea of the huge, honestly, API surface of temporal, you have a number of these classes that we're going to talk about in the next few slides. Just to briefly go over them, there's instant, which happens to exist in the exact time space. So it knows the exact time that it's happened since the epoch. And then there's a bunch of fuzzy time types. So there's plain date time, plain time, plain date. They happen to be all subsets of plain date time. So they talk about more fuzzy notions of time and dates. So, hey, 80 a.m. in the morning doesn't really matter how many exact nanoseconds have passed, right? And then there's a zone date type, which is sort of the ubermensch of all these types. It encompasses all the different use cases that we so far offer, and it can be completely replaced. It can replace totally date objects, but hopefully you would realize that you need something much less powerful. There's time zones and calendars, which sort of play between these. And then there's durations, which are used mostly for map.

To quickly summarize this, because this is going fast, but hopefully I'd be able to at least draw your attention in the span of 20 minutes, instance represent absolute points in time. So something as granular and as boring, as you may say, as a number of nanoseconds that have passed since the Epoch, which in this case is the Unix Epoch, 1970. And then there's the plane types, plane date time and friends who deal with the regular world clock time and calendar dates. So, for example, if you're building a fitness tracker, it doesn't really matter if I'm in Moscow or in Amsterdam. All that matters is that I wake up at 8 a.m. and eat a lot of bagels. Don't go for a run. Calendars refer to human calendars, so, you know, in common understanding, it would refer to the Gregorian calendar, which is pretty popular. It may refer to the more obscure calendars, but still used throughout the world, like the Buddhist calendar or the Hebrew calendar, Julian calendar, and then there's time zones that refer to an exact offset, so something like plus one hour from UTC or a more fuzzy human time zone, so something like Europe slash Amsterdam, which may represent different points of time depending on what time you're talking about and if it's summer or not. Zone date time, as I said, is the combination of an instant and a time zone, so it takes the boring instant and it pairs it with the time zone to project a date time from it, right? So if you know which time zone you're in and you know the exact number of nanoseconds that have passed, then you can give any information, you can tell me what time of the day it is and so on. It's the most powerful thing.

3. Building an Invoice Calculator with Tempo

Short description:

All arithmetic operations in this space are done in durations. Let's make an invoice calculator using Tempo. Step one is to pick a date time picker that returns an ISO 801 string. You can use libraries like React Types and Pickers or DateTimePickers for React and jQuery. Once you have two plain DateTime objects, you can find the difference between them.

Yeah, and then of course all the arithmetic operations that are done in this space are done in durations. So what is the difference between two dates or two times? Well, they're all durations. So enough talking, right? Let's get down to business. Let's make an invoice calculator, which happens to be a not so common application of dates and times, but it does happen to be sort of a power user in terms of computation. And let's see how simple it is with Tempo.

So step one, if I was posing a calculator like this, would be to pick a date time picker. So all the cool kids have told me that these days, you would pick a date time picker based on the rent-with-strategy. So whatever library you're using, you pick something based on that, right? The key point is that it should return an ISO 801 string. So this is the string persistence format that is accepted all over the Tempo API. It's standardized by ISO. And as long as it returns this format, you should be able to construct a Tempo type from this. Should it directly return a Tempo type? Probably. I mean, these libraries are written in JavaScript for JavaScript applications, right? So given that Tempo is the sort of future of Dates and Times in JavaScript, it makes sense that they could return Tempo types. I guess I could fork all these libraries and make versions of them that do this and make that become really popular. Or some of you could do it. That would be fun as well. There are already many that you can pick from. I went to NPM quickly and found out too. So there's React Types and Pickers. If you're using React, there's DateTimePickers if you're using jQuery, or nothing at all, which, I mean, it's just less so, but still jQuery. And yeah, you can drop any of these in. It could return an iso601 type, and you can use this string to construct a plain DateTime object in temporal. So temporal is the namespace. On the global, you can say temporal.plainDateTime.from, which is a static constructor method. It's a factory method. It takes in a convenient string format and pretends a plain DateTime object.

So once you have two plain DateTime objects right here, you're making an invoicing application. So you at least need two, a starting point and an ending point. So now that you have two DateTimes, you can find the difference between the two DateTimes. You can find out how much it worked.

4. Calculating Durations between Date Times

Short description:

When finding the difference between two date times, it's important to consider the directionality. Durations can be both positive and negative, so checking the sign is crucial. In the code example, the 'since' method calculates the duration from the receiver to the parameter, while the 'until' method calculates the duration from the parameter to the receiver. Once you have the durations, you can add them up to determine the total duration.

When you have a starting point and an ending point, you can find the difference by difference methods. And as we talked about, it's arithmetic. So the answer would be a duration.

Now, one key caveat that I want to talk about, one thing that you should note here is that durations can be both positive and negative. And the direction is important, especially when you're adding a number of durations. If you're adding 50 durations, then one of them is accidentally negative, and then you're not going to notice that the answer is a little off, and you end up charging less money, which you don't want to lose money, especially when you're dealing with money.

You should make sure that you can check the sign, the duration dot sign. Dot sign is a getter. And you can also find just the value. So whatever the sign is, it will return a positive result.

So let's see here. In this code example, we have two play date times. We have earlier, which is well, earlier. It's at midnight, and we have later, which is the same day, but four o'clock. So it's later. And just to notice the directionality here, there's two ways to find the difference.

There's later dot since earlier. So here later is the receiver, and earlier is the parameter, right? Because it's been X hours since earlier. And that would give you, you can put in what is the largest you want and the output, and it would give you a duration with four hours. Or you can say until. So because it's until, it means it's until later, right? So the sign reverses. This time earlier is the receiver, and this time we just said minutes. So it would give me 24 minutes, which is also four hours. If you change the objects, if you say later until earlier, it would be a negative result. We don't want a negative result because we did not work negative four hours.

And then once you have all these durations, you can find out how much it worked. Because you have an array of durations, you can add them all up. My friends who like functional programming, clean code might try a reduced method. I'm more sloppy. I tend to write code that looks like this.

5. Duration Creation and Manipulation

Short description:

You can create durations using different methods. The duration serialization format represents durations in a persistent format. It uses a pattern of P for period, followed by the units of time. Fractions can be used, but be cautious with JavaScript's handling of them. You can charge money based on the duration and perform mathematical operations using the total method. Remember that relativity is important.

So you can just have a for each loop or sort of a reduced method. One thing to see here is that we created zero durations using two different ways. So, in one, we just constructed a new temporal duration object. And in the second, we used the from method that we talked about from last time. If you notice here, I've used a spring format for the duration, pt 0s. And that was also sort of referred to in the last slides.

Let's talk about it in just a bit. But remember to call absolute if you say total.add duration.absolute, that just ignores the sign, which is something we probably need to do, right? To talk about this duration serialization format that I just talked about, durations can be a number of units, right? A duration could be one year, two months, three weeks. And all this duration can be represented in a spring by this persistence format. So it's P1Y2M. So if you see the pattern here, it's P, which is constant. It stands for period, if you're curious. So, period, one year, two months, 1Y2M, 3W for three weeks, four days. Then there's a T for time, and then five hours, six minutes, seven seconds, so on. One thing to note here is that this format can use fractions, so you can say something, you could totally say something like 2.5 months. But do keep in mind that it's probably a bit problematic because, so if you use the template polyfill, that I'm going to talk about in just a bit, it's written in JavaScript. JavaScript does not handle these numbers really well, because it is IEEE floats. Some of these fractions cannot be actually represented in JavaScript. So if you're using fraction, probably stick to these objects. But if you want, you can use the trim format.

So now that you have the duration, you can charge money by the hour, depending on the contract, actually, you might want to charge per day, per hour, per month, whatever the contract is, really. The math is easy. The math is so easy, in fact, that it's both inter-temporal. For all these related mathematical operations where you have a big duration and you want to bring it down to a single unit, you can just use the total method. So let's see here. I'm a widow who calculates the time I've worked in one, the second duration. So if I work a total of a million seconds, it actually just means that you can see I used the total method here to say that I want all this in unit hours, and it would give me 277.7. So that's how much I work. That's not a lot, but I like to calculate that in seconds. So once you have that, one last thing that I want you to remember is that relativity is important.

6. Understanding Time Relativity and Rounding

Short description:

We talked about the relativity of time and how it can vary depending on the context. For example, the number of months can have different lengths depending on the number of days in a month. Rounding is also important when dealing with durations, especially when charging based on a specific number of units. The concept of rounding can be used to calculate fees based on specific intervals. Additionally, a sandbox for a job application is available for exploration.

We talked about things like 2.5 months. Now 2.5, what's the meaning of 0.5 months, or even one month? It's really relative to what you're talking about. Right now, one month might mean 31 days. In February, one month might mean 28 days.

So, you know, an example would be that we can have a duration that has 2756 hours. And if you take that total, related to two different times, right? It's actually the same point in time. It's in this case it is 1st of January 2020 midnight, it's also 1st of January 2020 midnight here. But in this one, it is in the timezone Europe slash Rome, which, as you know, it's a real time zone that does the daylight savings. So, in this case, the number of months that have passed is slightly less. So, because they didn't have the daylight savings here, they didn't have the daylight savings here. So, some of these things do make sense, given relative to what we're talking about.

A quick example could be that in many places, if you take an unpaid vacation day off, you get paid a constant amount of money for every month, irrespective of how many days there were. But if we take a single unpaid day off, let's say, the money that they pay you less is actually dependent on the number of days that there were in that month. So, taking an unpaid day off in July is technically much cheaper than taking one in February. So, all these things, of course, need to be taken into account. That's why you can use relative to provide exactly the what you were up to.

And next off you have rounding. So, now that we have all these things, the final value can just be rounded up or down depending on what contract we're talking about. But sometimes you don't charge by a single unit, right? You don't charge by every hour or every day, but you charge by a number of Xs, right? A number of days and a number of hours. And, if you think about it, charging by the day is technically that, right? When I say I charge per day, that means that I charge per eight hours. That doesn't mean that I'm talking about charging for 24 hour checks. So, this gives you a sort of more powerful method called round. And, unlike total, you can do more fun things with it. So, let's say that I had a six minute appointment with an immigration lawyer, and the immigration lawyer actually charges per every five minutes, and of course, they round up. So, if I spend six minutes with them, actually, I need to pay them double the amount if I just talked a little faster, which is why I should talk faster now. But, that's all fun stuff. We talked a lot. I had a lot of fun, but now it's time to do something that's more practical. So, I'm pretty sure a few of you had your phones out, but if you scan that QR code, I can show you that for a bit more, you will find this sandbox that I made for you. And this is the fun stuff, right? The code sandbox is actually about a job application so you can fill stuff up like the date of birth and where you work from and where to.

7. Calculating Methods with Tempo

Short description:

And it calculates a bunch of stuff. The calculate age method is written using the moment API, while the calculate time to interview is written using the Luxon API. Your task is to rewrite all these methods using Tempo. Follow the comments and forward the sandbox. The new code will be more efficient, concise, and logical. I'm excited to see the solutions you come up with.

And it calculates a bunch of stuff. It's just an example. But the fun stuff is the calculate age method on this one is written using the moment API. The calculate time to interview is written using the Luxon API. And calculate job experiences is written using plain old date. And your job now is to actually rewrite all these methods.

There's links to the docs all over the place. And you need to follow the comments. And you need to forward this sandbox and write the code using tempo. Maybe you can just comment it out and see the new code. But you'd see a bigger improvement. And you'd see less code. And you'd see code that makes more sense to you, hopefully. But yeah, I'd love to see what solutions you've come up with for these.

So let's quickly go back to my slides. Okay. My slides. Let's quickly go back to this. Okay. So you can scan that. And if I'm there, I'll probably just paste the link to the chat. And quickly links to the future and present, I'd send you links to these slides as well. So you can click around these. Here's a link to the polyfill. We're using this polyfill also in the poke sandbox. So this is a polyfill that we came up with that can poke champions. It's sort of a reference implementation and it works. It should be, it should work in production as well. So you can follow that. There's a issue on V8 for, for Vent10 with LAN in Chromium and Chrome and Edge and all your favorite browsers.

8. Temporal V2 Repository and Gratitude

Short description:

Spiderman 3 for Firefox, JavaScript core refreshing, Temporal V2 repository for new ideas, thanks to Temporal Champions, Moments.js maintainers, event organizers, and Oga for code sandbox.

And also Spiderman 3 for Firefox, which is my favorite browser. And you can keep refreshing these JavaScript core if you like Safari. And I try to refresh them every five minutes to see if there's any progress.

But there is a repository for Temporal V2 for all the new ideas that we're coming up with for sort of a future extension to this. And just quickly need to thank a bunch of people. I want to thank the Temporal Champions for working on all these special things. The Moments.js maintainers for kick-starting the original proposal. And the organizers in PC for inviting me and for facilitating this entire event. And Oga for helping me build the code sandbox. Thank you, everyone. But last but not least, thank you.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
As developers, we spend much of our time debugging apps - often code we didn't even write. Sadly, few developers have ever been taught how to approach debugging - it's something most of us learn through painful experience.  The good news is you _can_ learn how to debug effectively, and there's several key techniques and tools you can use for debugging JS and React apps.

Workshops on related topic

React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
React Summit US 2023React Summit US 2023
96 min
Build a powerful DataGrid in few hours with Ag Grid
WorkshopFree
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.
We all know that rolling our own grid solution is not easy, and let's be honest, is not something that we should be working on. We are focused on building a product and driving forward innovation. In this workshop, you'll see just how easy it is to get started with AG Grid.
Prerequisites: Basic React and JavaScript
Workshop level: Beginner
Node Congress 2023Node Congress 2023
49 min
JavaScript-based full-text search with Orama everywhere
Workshop
In this workshop, we will see how to adopt Orama, a powerful full-text search engine written entirely in JavaScript, to make search available wherever JavaScript runs. We will learn when, how, and why deploying it on a serverless function could be a great idea, and when it would be better to keep it directly on the browser. Forget APIs, complex configurations, etc: Orama will make it easy to integrate search on projects of any scale.
Node Congress 2022Node Congress 2022
128 min
Back to the basics
WorkshopFree
“You’ll never believe where objects come from in JavaScript.”
“These 10 languages are worse than JavaScript in asynchronous programming.”
Let’s explore some aspects of JavaScript that you might take for granted in the clickbaitest nodecongress.com workshop.
To attend this workshop you only need to be able to write and run NodeJS code on your computer. Both junior and senior developers are welcome.
Objects are from Mars, functions are from Venus
Let’s deep-dive into the ins and outs of objects and then zoom out to see modules from a different perspective. How many ways are there to create objects? Are they all that useful? When should you consider using them?
If you’re now thinking “who cares?“, then this workshop is probably for you.
Asynchronous JavaScript: the good? parts
Let’s have an honest conversation.
I mean… why, oh why, do we need to bear with all this BS? My guess is that it depends on perspective too. Let’s first assume a hard truth about it: it could be worse… then maybe we can start seeing the not-so-bad-even-great features of JavaScript regarding non-blocking programs.