How to Initialize a Date with a Time Zone in JavaScript

initialize a Date with a time zone in JavaScript

In this article, you will learn how to initialize a Date with a time zone in JavaScript by using the Intl class of the ECMAScript API.

Initialize a date with time zone using javascript

Understanding the Date class

The Date class will always use UTC (Coordinated Universal Time) as its date format and takes an inputted time stamp (or none at all) and return it in your computer’s set time zone.

For anyone who doesn’t remember, UTC is the international standard for time.

Though something to note is that a Date class is ultimately just a number that describes how many milliseconds it has been since 1970-01-01 00:00:00 UTC (disregarding leap seconds). Another thing is that the Date class does not have any time zone or string formats, and simply use your computer’s set time zone for its functions and the like.

Using the Intl class (ECMAScript and other APIs)

The ECMAScript is a JavaScript standard that “defines the application programming interface for ECMAScript objects that support programs that need to adapt to the linguistic and cultural conventions used by different human languages and countries.” according to the ECMAScript documentation website here.

Though most importantly, ECMAScript provides the Intl class, which provides international language-sensitive formatting for numbers and date-time, among other things.

We’ll use the Object.toLocaleString() function, which returns a string formatted to the specified format representing the original Object. In this case, it will return the date of a specified locale formatted to a locale.

Syntax:

Object.toLocaleString(string locale, Object? identifier)

Parameters:

NameTypeDescription
localestringThe specified format to format the original Object to
optionsObject? ({})Optional. Specifies a locale.

Code:

// January 21st 2022 00:00AM UTC+7
const date = new Date("2022-01-21T00:00:00.000+07:00");
console.log(date.toLocaleString());

// January 20th 2022 00:00AM UTC-5
const remote_date = date.toLocaleString('en-US', { timeZone: 'America/New_York' });
console.log(remote_date);

Output:

1/21/2022, 12:00:00 AM
1/20/2022, 12:00:00 PM

One thing to note is that you can specifically get the time and date respectively by using the Date.toLocaleDateString() and Date.toLocaleTimeString() respectively.

You can view a more detailed description of the arguments here.

Summary

A Date class is only uses your computer’s specified time zone to perform its functions, so to initialize a Date with a time zone in JavaScript, you need to use the Intl class of the ECMAScript API. Specifically the Object.toLocaleString() function while specifying both the format and locale.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *