Temporal: Modern Dates and Times in JavaScript

Rate this content
Bookmark
SlidesGithub

Ever been fooled by one of the many pitfalls of the JS Date object? Do you bundle time zone data? Then check out Temporal! Temporal is a TC39 proposal currently being implemented in JS engines, that brings better date and time handling, and time zone awareness, to JS. This talk is a tour of what you need to know about Temporal, walking through one simple, one medium, and one complicated task each solved with Temporal.

This talk has been presented at JSNation US 2024, check out the latest edition of this JavaScript Conference.

FAQ

Temporal introduces several types including Instant, PlainDate, PlainTime, PlainYearMonth, PlainMonthDay, ZonedDateTime, and Duration, each serving different purposes in date and time representation.

Temporal provides arithmetic methods such as add, subtract, since, and until, allowing precise duration calculations and adjustments across different types of date and time representations.

Temporal introduces the ZonedDateTime type, which accounts for time zones and daylight saving time changes, providing accurate representation of exact moments in time with time zone rules.

Temporal provides a strongly typed and immutable approach to date and time management, with support for non-Gregorian calendars and better integration with JavaScript's internationalization facilities.

Developers can explore the Temporal API through its documentation, and once it graduates, it will be available on MDN alongside other JavaScript built-ins.

The Temporal proposal adds modern date and time handling to JavaScript, providing a built-in library for dates and times similar to those in other programming languages.

The Instant type represents an exact time point on the timeline with nanosecond precision, without any calendar or time zone information.

Temporal aims to address the deficiencies of the existing Date object in JavaScript, such as unwieldy APIs and mutability issues, by providing a more robust and strongly typed system for date and time management.

Yes, Temporal is designed to support non-Gregorian calendars, allowing developers to accurately handle dates in various cultural and regional contexts.

Temporal objects are immutable to prevent unwanted modifications by external code, enhancing reliability and predictability in date and time operations.

 Philip Chimento
Philip Chimento
22 min
21 Nov, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
I'll speak today about the Temporal proposal, which adds modern date and time handling to JavaScript. Temporal is an API that'll be available in browsers soon and will add a built-in library for dates and times, avoiding the need for external libraries like Moment. It offers strong typing with different types for different data, such as calendar dates with or without time. Temporal objects are immutable and designed to work with JavaScript's internationalization facilities. It addresses deficiencies in the global Date object and introduces types like instant and plain types for accurate representation of time and dates across time zones. With the old Date, representing a date without a time can be problematic, especially in time zones where midnight is skipped due to daylight saving time. Temporal introduces types like PlainDate, PlainTime, PlainYearMonth, PlainMonthDay, and ZonedDateTime to accurately represent different scenarios. Additionally, there is a type called Duration for arithmetic operations and unit conversion. Now that I've introduced you to the cast of characters in Temporal, it's time to show how to accomplish a programming task. We'll start with an easy task: getting the current time as a timestamp in milliseconds using the instant type. To convert between Temporal types, you can either drop or add information. The toZonedDateTime method is used for conversion and requires adding a time zone and a time. Although Temporal objects are immutable, you can create new objects with replaced components using the with method. Migrating from the old Date object to Temporal offers a more reliable solution and avoids potential bugs. Check out the documentation for more details and enjoy using Temporal in your codebase!

1. Introduction to Temporal Proposal

Short description:

I'll speak today about the temporal proposal, which adds modern date and time handling to JavaScript. Temporal is an API that'll be available in browsers soon and will add a built-in library for dates and times, avoiding the need for external libraries like Moment. It offers strong typing with different types for different data, such as calendar dates with or without time.

Hi, my name is Philip Chimento. I work as a JavaScript engine developer at Igalia. I'll speak today about the temporal proposal, which adds modern date and time handling to JavaScript. I'm part of a group working on this proposal, and my participation is part of a partnership between Igalia and Bloomberg.

In this presentation, I'll give you a tour through the API and show you what you can do with temporal by means of walking you through an easy, medium, and a complicated programming task. So, if you are asking what is temporal, it's an API that's been proposed to become part of JavaScript. It'll be available in browsers soon. And it'll add a built-in library for dates and times, like many other programming languages already have.

So, when I say it's built in, I mean it's part of your browser or of your JavaScript engine. That's important because many developers include a dependency on Moment or some similar library in their app to achieve the same thing that you could with temporal. But depending on how much locale data you include, that could add a payload of anywhere from a dozen to 200 kilobytes to your app. And with built-in, you avoid that. Temporal is strongly typed. That means that for different kinds of data, such as a calendar date with or without an associated time, there are different types to represent them, instead of one type fits all.

2. Exploring Temporal Types

Short description:

Temporal objects are immutable and designed to work with JavaScript's internationalization facilities. It addresses deficiencies in the global date object and introduces types like instant and plain types for accurate representation of time and dates across time zones.

Temporal objects are immutable, and that means that you don't have to worry about code that you don't own modifying your objects without your knowledge. And lastly, it's designed to work together with JavaScript's internationalization facilities. And it provides things that a lot of other libraries don't, such as non-Gregorian calendars.

So, a fair question for any addition to the JavaScript language is, do we really need this? Like, we already have the global date object. It's not perfect, but it's done okay for all these years. And I'm going to disagree with what I just said. We do actually have a good list of Date's deficiencies. This here is a list of problems with dates that were identified way back at the beginning that Temporal aims to solve.

I won't go into all of these. Some of them, such as the unwieldy APIs, could be fixed, but others like mutability can't be fixed without breaking the web, because there's so much code out there that already relies on the existing behavior. The original JavaScript Date was based on a Date class from Java, which Java deprecated in 1997 and replaced by something better. And a quarter century later, we're now doing the same thing in JavaScript.

So, I mentioned strong typing. For the next few slides, I'll give you a tour through these types that Temporal introduces. The first type you should know about is instant. It represents what we call an exact time, an instantaneous point on the timeline with nanosecond resolution. There's no calendar, so no months, weeks, years, or days. No time zone, so no daylight saving adjustments. Just purely an ever-increasing number.

Next, we have a family of types called the plain types. These represent a date on your wall calendar and a time on your wall clock, which we call wall time for short. These represent your local date and time independent of time zone, and so there are no daylight saving adjustments. But unlike instant, they're not exact moments in time. A wall time like November 18th, 2024 at 2.30 occurs at several different exact times around the world. So, this is just purely the numbers that you see on your wall. So, why do we have this family of plain types or wall types with progressively less information? This is so that you can correctly represent the information that you have. For example, with the old Date, if you wanted to represent a date without a time, you might use midnight in the user's local time zone. But there are actually days in certain time zones where midnight is skipped due to daylight saving time.

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

Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
Watch video: Debugging JS
Debugging JavaScript is a crucial skill that is often overlooked in the industry. It is important to understand the problem, reproduce the issue, and identify the root cause. Having a variety of debugging tools and techniques, such as console methods and graphical debuggers, is beneficial. Replay is a time-traveling debugger for JavaScript that allows users to record and inspect bugs. It works with Redux, plain React, and even minified code with the help of source maps.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
WebAssembly enables optimizing JavaScript performance for different environments by deploying the JavaScript engine as a portable WebAssembly module. By making JavaScript on WebAssembly fast, instances can be created for each request, reducing latency and security risks. Initialization and runtime phases can be improved with tools like Wiser and snapshotting, resulting in faster startup times. Optimizing JavaScript performance in WebAssembly can be achieved through techniques like ahead-of-time compilation and inline caching. WebAssembly usage is growing outside the web, offering benefits like isolation and portability. Build sizes and snapshotting in WebAssembly depend on the application, and more information can be found on the Mozilla Hacks website and Bike Reliance site.
Webpack in 5 Years?
JSNation 2022JSNation 2022
26 min
Webpack in 5 Years?
Top Content
In the last 10 years, Webpack has shaped the way we develop web applications by introducing code splitting, co-locating style sheets and assets with JavaScript modules, and enabling bundling for server-side processing. Webpack's flexibility and large plugin system have also contributed to innovation in the ecosystem. The initial configuration for Webpack can be overwhelming, but it is necessary due to the complexity of modern web applications. In larger scale applications, there are performance problems in Webpack due to issues with garbage collection, leveraging multiple CPUs, and architectural limitations. Fixing problems in Webpack has trade-offs, but a rewrite could optimize architecture and fix performance issues.
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
There is a need for a standard library of APIs for JavaScript runtimes, as there are currently multiple ways to perform fundamental tasks like base64 encoding. JavaScript runtimes have historically lacked a standard library, causing friction and difficulty for developers. The idea of a small core has both benefits and drawbacks, with some runtimes abusing it to limit innovation. There is a misalignment between Node and web browsers in terms of functionality and API standards. The proposal is to involve browser developers in conversations about API standardization and to create a common standard library for JavaScript runtimes.

Workshops on related topic

Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Top Content
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
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.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
Top Content
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
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.
React Server Components Unleashed: A Deep Dive into Next-Gen Web Development
React Day Berlin 2023React Day Berlin 2023
149 min
React Server Components Unleashed: A Deep Dive into Next-Gen Web Development
Workshop
Maurice de Beijer
Maurice de Beijer
Get ready to supercharge your web development skills with React Server Components! In this immersive, 3-hour workshop, we'll unlock the full potential of this revolutionary technology and explore how it's transforming the way developers build lightning-fast, efficient web applications.
Join us as we delve into the exciting world of React Server Components, which seamlessly blend server-side rendering with client-side interactivity for unparalleled performance and user experience. You'll gain hands-on experience through practical exercises, real-world examples, and expert guidance on how to harness the power of Server Components in your own projects.
Throughout the workshop, we'll cover essential topics, including:- Understanding the differences between Server and Client Components- Implementing Server Components to optimize data fetching and reduce JavaScript bundle size- Integrating Server and Client Components for a seamless user experience- Strategies for effectively passing data between components and managing state- Tips and best practices for maximizing the performance benefits of React Server Components
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
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