Learn how to Work With Time Zones in JavaScript

0
3


For a very long time our civilization has used the relative place of solar within the sky to find out what time it’s at a particular second in the course of the day. Nevertheless, the place of solar within the sky varies for various places on earth even on the similar level of time. For instance, what is perhaps afternoon in India can be near midnight in the USA.

I used an excessive instance above however utilizing the solar as a foundation to determine what time it’s can lead to totally different cities having totally different time even when they aren’t a lot additional aside. This can lead to a wide range of issues resembling scheduling conflicts. To illustrate you determine to video chat together with your buddy at 9:30 within the morning. Nevertheless, their 9:30 shall be totally different than yours. Time zones develop into vital for lengthy distance journey or communication.

One answer to this drawback is using time zones. A time zone is any area of the Earth with the identical customary time.

On this tutorial, we are going to be taught a little bit bit about time zones and how you can work with time zones in JavaScript.

Understanding the Fundamentals of Time Zones

As I discussed earlier, some components of the Earth will expertise midday whereas others have midnight. Subsequently, it does not make sense for your entire Earth to function on the identical time.

The Earth has been divided into 24 time zones to resolve this problem. All factors that fall inside the similar time zone may have the identical time.

We start with the belief of a Coordinated Common Time or UTC which represents Greenwich Imply Time. UTC doesn’t change because of daylight saving time or regional variations. This makes UTC a widely-used time customary for any duties that require scheduling over continental distances.

A flight that leaves London at 5:00 UTC will imply the identical factor in Sydney, Australia and Los Angeles, United States.

An offset is added to the UTC to point that we’re transferring hours forward (+) or hours behind (-) as we cross longitudes. For instance, Japan has Japan Commonplace Time which interprets to UTC+9:00. Samoa has Samoa Commonplace Time which is UTC-11:00.

Not all nations and areas strictly comply with the conference of longitudinal traces to divide themselves in time zones. For instance, geographically giant nations resembling India and China nonetheless observe a single customary time. India may have a number of time zones however it follows Indian Commonplace Time which is UTC+5:30. Equally, China follows China Commonplace Time which is UTC+8:00.

Every time we discuss time, you will need to point out the time zone if we’re speaking with locations which are geographically far aside.

The Date Object and Time Zones in JavaScript

The Date object in JavaScript mainly represents the variety of milliseconds which have handed for the reason that midnight firstly of January 1, 1970 UTC. This worth is timezone-agnostic which mainly means that it’ll keep the identical throughout time zones.

These variety of elapsed seconds are additionally known as timestamp. The utmost and minimal worth of timestamp is ±8,640,000,000,000,000. This covers dates starting from April 20, 271821 BC to September 13, 275760 AD. That is plenty of time!

It’s attainable to get the timestamp worth for a date by utilizing the getTime() technique. This technique is time zone agnostic. Listed below are some examples:

1
let now_india = new Date();
2

3
// Outputs: Date Thu Jun 08 2023 09:43:04 GMT+0530 (India Commonplace Time)
4
console.log(now_india);
5

6
// Outputs:  1686197601087
7
console.log(now_india.getTime());
8


Now I will change my system time zone to Wellington and name getTime() once more.

1
let now_wellington = new Date();
2

3
// Outputs: Date Thu Jun 08 2023 16:13:21 GMT+1200 (New Zealand Commonplace Time)
4
console.log(now_wellington);
5

6
// Outputs: 1686197601087
7
console.log(now_wellington.getTime());

The getTime() values differ a little bit bit as a result of delay in switching of time zones. Nevertheless, you may see that the distinction is not as enormous as it will be if getTime() truly relied on native system time.

One other vital factor to notice right here is that logging the values of now_india and now_wellington to the console ends in the output of date and time with their respective time zones.

Getting the Time Parts in UTC

Since UTC is the reference towards which the time in different zones is represented, you may wish to get the worth of various parts of time in UTC once in a while.

Thankfully, there are a number of strategies that can assist you try this.

  1. getUTCFullYear() gives you the yr for a specific date in accordance with common time.
  2. getUTCMonth() gives you the month for a specific date in accordance with common time.
  3. getUTCDate() gives you the day of the month for a specific date in accordance with common time.
  4. getUTCHours() gives you the hours for a specific date in accordance with common time.
  5. getUTCMinutes() gives you the minutes for a specific date in accordance with common time.
  6. getUTCSeconds() gives you the seconds for a specific date in accordance with common time.

The next code snippet reveals how the output of those strategies can differ from common strategies that return native values for particular dates.

1
let newyear_india = new Date('2024-01-01T01:20:30.000+05:30');
2

3
// Outputs: New 12 months in India: Tue Jan 01 2024 01:20:30 GMT+0530 (India Commonplace Time)
4
console.log(`New 12 months in India: ${newyear_india}`);
5

6
// Outputs: 12 months in India: 2024 | 12 months in UTC: 2023
7
console.log(`12 months in India: ${newyear_india.getFullYear()} | 12 months in UTC: ${newyear_india.getUTCFullYear()}`);
8

9
// Outputs: Month in India: 0 | Month in UTC: 12
10
console.log(`Month in India: ${newyear_india.getMonth()} | Month in UTC: ${newyear_india.getUTCMonth()}`);
11

12
// Outputs: Date in India: 1 | Date in UTC: 31
13
console.log(`Date in India: ${newyear_india.getDate()} | Date in UTC: ${newyear_india.getUTCDate()}`);
14

15
// Outputs: Hours in India: 1 | Hours in UTC: 19
16
console.log(`Hours in India: ${newyear_india.getHours()} | Hours in UTC: ${newyear_india.getUTCHours()}`);
17

18
// Outputs: Minutes in India: 20 | Minutes in UTC: 50
19
console.log(`Minutes in India: ${newyear_india.getMinutes()} | Minutes in UTC: ${newyear_india.getUTCMinutes()}`);
20

21
// Outputs: Seconds in India: 30 | Seconds in UTC: 30
22
console.log(`Seconds in India: ${newyear_india.getSeconds()} | Seconds in UTC: ${newyear_india.getUTCSeconds()}`);

Output Date and Time for Completely different Locales and Time Zones

The Date object in JavaScript has a couple of helpful strategies that enable us to current any explicit date utilizing particular locales inside the time zones we wish.

Completely different nations write the months, years, and days for a date in a different way. You should utilize the toLocaleDateString() technique with a view to return a string that comprises language-specific illustration of the given date within the time zone of the person.

Right here is an instance:

1
let now = new Date('2024-12-31T00:00:00+00:30');
2
const choices = { weekday: 'brief', yr: 'numeric', month: 'lengthy', day: 'numeric' };
3

4
// Outputs: 31/12/2024
5
console.log(now.toLocaleDateString('en-IN'));
6

7
// Outputs: Tue, 31 December, 2024
8
console.log(now.toLocaleDateString('en-IN', choices));
9

10
// Outputs: 12/31/2024
11
console.log(now.toLocaleDateString('en-US'));
12

13
// Outputs: Tue, December 31, 2024
14
console.log(now.toLocaleDateString('en-US', choices));
15

16
// Outputs: Tue, 31 December 2024
17
console.log(now.toLocaleDateString('en-GB', choices)); 

As you may see, a change within the locale had no impact on the time zone. In any other case, the date would have been totally different for United States. The time zone stays no matter it’s on the native machine which is IST on this case.

You should utilize the toLocaleString() technique to get a string illustration of all of the parts within the Date object. The tactic accepts two non-obligatory parameters. First one is the locales and may have values like en-US, en-AU, and de-DE and so forth. The second parameter is the choices object which controls how the knowledge is exhibited to the person.

Right here is an instance of utilizing this technique:

1
let now = new Date();
2

3
let now_india = now.toLocaleString("en-IN", {
4
    dateStyle: "medium",
5
    timeStyle: "medium",
6
    timeZone: "Asia/Kolkata"
7
});
8
doc.querySelector("p.india").innerText = now_india;
9

10
let now_sydney = now.toLocaleString("en-AU", {
11
    dateStyle: "medium",
12
    timeStyle: "medium",
13
    timeZone: "Australia/Sydney"
14
});
15
doc.querySelector("p.aus").innerText = now_sydney;
16

17
let now_new_york = now.toLocaleString("en-US", {
18
    dateStyle: "medium",
19
    timeStyle: "medium",
20
    timeZone: "America/New_York"
21
});
22
doc.querySelector("p.us").innerText = now_new_york;

We start by storing a Date object in our variable now. This represents the present native date and time on the execution of the code. After that, we use the toLocaleString() technique to get a illustration of that date in our most popular locale and time zone. The returned string is finally used to set worth of the innerText property for a bunch of p parts.

You possibly can wrap the above code in a operate known as updateTime() and use the code under to create three clocks that present time from three main cities around the globe.

1
updateTime();
2
setInterval(updateTime, 1000);

This is a CodePen that I’ve put collectively to exhibit this performance:

Remaining Ideas

Fairly a couple of issues that we do in our day-to-day lives depend upon realizing the proper date and time both at our current location or some place else far-off. This tutorial started with a quick introduction of the necessity and use of time zones. After that, we moved on to the precise job a hand, studying how you can work with time zones in JavaScript.

Quite a lot of built-in strategies of the JavaScript Date object give outcomes primarily based on the native time. Nevertheless, there are some UTC particular strategies in addition to strategies like toLocaleString() that show you how to convert any date right into a locale and time zone particular model.

LEAVE A REPLY

Please enter your comment!
Please enter your name here