How to handle timezones with JavaScript

6 min read

In this post, we will spend time learning how to handle timezones with JavaScript. This will be useful when using the Nylas Node SDK to manage calendar events. We’ll first discuss how to work with date and time using JavaScript API and take a look at working with Nylas calendar events to display different timezones.

Prerequisite

Sign up here if you need to create a Nylas account for free! Follow the Quickstart to receive your account credentials. Ensure to save the access token to use below.

Environment

We are going to use the Nylas Command Line Interface (CLI) to access a calendar events. Check out Working with the Nylas CLI to learn more.

Working with dates/timezones in JavaScript

The Javascript Date object provides a value that is relative to a reference point in time. As an example, let’s look at the following, try running this in the browser:

> Date.now();
> 1656423761569

Running Date.now() returns the time in milliseconds since January 1, 1970, Universal Time Coordinated (UTC). This is also known as Unix time, however, the difference is that Unix time is in seconds and JavaScript returns a value in milliseconds.

The Date object returns different formats. Take a look at Mozilla’s documentation on using the Date object. Here are a few more examples run in the browser:

> new Date();
> Tue Jun 28 2022 09:47:44 GMT-0400 (Eastern Daylight Time)

> const date = new Date();
> date.toISOString();
> '2022-06-28T13:47:44.122Z'

One thing to keep in mind when working with date and time is that the display format will be different from the format the information is stored in.

We will need to work with two or more formats, here is a non-exhaustive list of possible scenarios:

  • a format for displaying to the user
  • a format for programming and storing in a database
  • a format provided by a third-party API like Nylas

In most cases, we can program and store date and time as a Unix timestamp or as an ISO 8601 format, which can be parsed by the JavaScript Date object.

When displaying a date, we can consider using the Intl object provided by JavaScript. Take a look at Mozilla’s documentation on using the Intl object. Here are a few examples run in the browser:

> const date = new Date();
> console.log(new Intl.DateTimeFormat('en-US').format(date));
> 6/28/2022
> console.log(new Intl.DateTimeFormat('en-GB').format(date));
> 28/06/2022
> console.log(new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format(date));
> R4/6/28

As you see, we provided locale arguments (en-US, en-GB, ja-JP-u-ca-japanese), to get dates formatted for different countries. You can read more about using different locales from Mozilla’s documentation.

Now we’ve explored working with date and time using the Date and Intl objects provided by the JavaScript API.

JavaScript date/timezone libraries

So far we’ve covered working with date and time using the Javascript API alone, and this is not the most popular path for JavaScript developers. It is important to understand what’s available out of the box. So what do JavaScript developers use when working with date and time?

The JavaScript ecosystem has many date libraries, here are a few recommendations:

Using the JavaScript API can be problematic in a few scenarios, which is why quite a few open-source date and time alternatives exist. This is something to keep in mind as we will end up using dates in at least two different environments (Node and Browser). In future releases of JavaScript, we will have access to the Temporal object, a modern date and time API.

Now we’ve discussed using libraries when working with date and time in JavaScript.

Working with Nylas calendar events

Let’s take a look at Nylas calendar events and how we can work with the date and time information provided to us. We are going to use the Nylas CLI to access a calendar events. You can learn about the CLI by checking out Working with the Nylas CLI.

$ nylas api events get --limit=1 --calendar_id=<CALENDAR_ID> --starts_after=<STARTS_AFTER>

[
    {
        "account_id": "<ACCOUNT_ID>",
        "busy": true,
        "calendar_id": "<CALENDAR_ID>",
        "conferencing": {
            "details": {
                "meeting_code": "<MEETING_CODE>",
                "phone": [
                    "<PHONE>"
                ],
                "url": "<URL>"
            },
            "provider": "Meeting"
        },
        "customer_event_id": null,
        "description": "Description",
        "hide_participants": false,
        "ical_uid": "<I_CAL_ID>",
        "id": "<EVENT_ID>",
        "location": null,
        "master_event_id": "<MASTER_EVENT_ID>",
        "message_id": null,
        "object": "event",
        "original_start_time": 1656439200,
        "owner": "<OWNER_EMAIL>",
        "participants": [
            {
                "comment": null,
                "email": "<EMAIL_1>",
                "name": null,
                "phone_number": null,
                "status": "yes"
            },
            {
                "comment": null,
                "email": "<EMAIL_2>",
                "name": null,
                "phone_number": null,
                "status": "yes"
            }
        ],
        "read_only": false,
        "reminders": null,
        "status": "confirmed",
        "title": "Working with Calendar and date/time",
        "visibility": null,
        "when": {
            "end_time": 1656441900,
            "object": "timespan",
            "start_time": 1656439200
        }
    }
]

If you are running the CLI command, make sure to update the following:

  • CALENDAR_ID is a calendar ID that you have access to
  • STARTS_AFTER is recommended to be after today (or this morning) as a Unix timestamp so you can see upcoming events

If everything worked, you will see a calendar event returned with a when object that contains end_time and start_time as a timespan. This is a meeting so the event will have a start and end time.

Taking a look at the Nylas API docs, the time values are provided as a Unix timestamp, which is in seconds, not milliseconds. So to use these values in JavaScript API, we need to convert the time to milliseconds as follows:

> const startTime = new Date(1656439200 * 1000)
> const endTime = new Date(1656441900 * 1000)

We’ve now created two variables that store the start and end times as a JavaScript Date object. We can convert the start_time to different timezones as follows:

> startTime.toLocaleString('en-US', { timeZone: 'America/Vancouver'})
> '6/28/2022, 11:00:00 AM'
> startTime.toLocaleString('en-US', { timeZone: 'America/Toronto'})
> '6/28/2022, 2:00:00 PM'

These are a few examples of working with the time provided by the Nylas calendar API. We recommend exploring the use of a date/time library as this will simplify development when working with different timezones.

Now we’ve discussed working JavaScript’s Date object when working with Nylas calendar events.

Build Time!

You can find example code on the Nylas Samples code repository. Continue building with Nylas and learn more by visiting the Node SDK documentation.

You can sign up Nylas for free and start building!

Related resources

How to create an appointment scheduler in your React app

Learn how to create an appointment scheduler in your React app using Nylas Scheduler. Streamline bookings and UX with step-by-step guidance.

Beyond APIs: Designing elegant, smart Web Components

Dive into the world of smart Web Components for advanced API integration solutions. Design elegant, customizable elements to elevate user experiences.

How to integrate a React calendar component to streamline scheduling

Elevate your app’s scheduling with a React calendar component and seamlessly integrate with Nylas for efficient calendar management.