Wednesday, December 6, 2023
HomeVideo EditingThe best way to Work With Time Zones in JavaScript

The best way to Work With Time Zones in JavaScript


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. Nonetheless, the place of solar within the sky varies for various places on earth even on the similar level of time. For instance, what could be afternoon in India could be near midnight in the US.

I used an excessive instance above however utilizing the solar as a foundation to resolve what time it’s may end up in totally different cities having totally different time even when they aren’t a lot additional aside. This may end up in a wide range of issues reminiscent of scheduling conflicts. For instance you resolve to video chat along with your buddy at 9:30 within the morning. Nonetheless, their 9:30 can be totally different than yours. Time zones develop into necessary for lengthy distance journey or communication.

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

On this tutorial, we’ll study a little bit bit about time zones and the way to work with time zones in JavaScript.

Understanding the Fundamentals of Time Zones

As I discussed earlier, some elements of the Earth will expertise midday whereas others have midnight. Due to this fact, it would not make sense for the whole Earth to function on the identical time.

The Earth has been divided into 24 time zones to resolve this subject. All factors that fall inside the similar time zone can 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 resulting from 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 international locations and areas strictly observe the conference of longitudinal traces to divide themselves in time zones. For instance, geographically massive international locations reminiscent of 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 can be geographically far aside.

The Date Object and Time Zones in JavaScript

The Date object in JavaScript principally represents the variety of milliseconds which have handed because the midnight in the beginning of January 1, 1970 UTC. This worth is timezone-agnostic which principally means that it’s going to keep the identical throughout time zones.

These variety of elapsed seconds are additionally referred to 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 numerous time!

It’s doable to get the timestamp worth for a date through the use of the getTime() technique. This technique is time zone agnostic. Listed here 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 am going to 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. Nonetheless, you’ll be able to see that the distinction is not as big as it will be if getTime() really relied on native system time.

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

Getting the Time Elements in UTC

Since UTC is the reference towards which the time in different zones is represented, you would possibly need to get the worth of various elements of time in UTC once in a while.

Luckily, there are a selection of strategies that will help you do this.

  1. getUTCFullYear() will provide you with the yr for a specific date in accordance with common time.
  2. getUTCMonth() will provide you with the month for a specific date in accordance with common time.
  3. getUTCDate() will provide you with the day of the month for a specific date in accordance with common time.
  4. getUTCHours() will provide you with the hours for a specific date in accordance with common time.
  5. getUTCMinutes() will provide you with the minutes for a specific date in accordance with common time.
  6. getUTCSeconds() will provide you with 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 Yr in India: Tue Jan 01 2024 01:20:30 GMT+0530 (India Commonplace Time)
4
console.log(`New Yr in India: ${newyear_india}`);
5

6
// Outputs: Yr in India: 2024 | Yr in UTC: 2023
7
console.log(`Yr in India: ${newyear_india.getFullYear()} | Yr 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 permit us to current any specific date utilizing particular locales inside the time zones we would like.

Completely different international locations 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 accommodates 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: 'quick', 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’ll be able to 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 elements within the Date object. The strategy accepts two non-obligatory parameters. First one is the locales and may have values like en-US, en-AU, and de-DE and so on. The second parameter is the choices object which controls how the data 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 well-liked 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 perform referred to 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 display this performance:

Last Ideas

Fairly a couple of issues that we do in our day-to-day lives rely upon understanding the proper date and time both at our current location or someplace else distant. 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 the way to work with time zones in JavaScript.

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments