There are many javascript libraries that allow you to convert the timezone with ease.
However, you might don't want to include the whole library if you just want to convert a couple times.
So this video will talk about converting timezone in pure javascript. It's short and easy too!
Let's start with creating a new Date object
This will get us a local time. Let's put it on console to see
Currently I'm in SE Asia timezone which is +7 hours from UTC
If we want to convert the local time to any timezone, we need to convert it to UTC time first. Then add the destination timezone offset to the converted UTC time
To convert local time to UTC time- we need to get the local timezone offset from UTC with getTimezoneOffset()
I'm going to display the offset to the console
It returned -420 which is our local timezone offset from UTC in "minutes" (-420 / 60 = 7 hours)
Minus sign means this timezone is ahead of UTC
Now we'll add UTC offset to our local time
which we'll get the UTC time as a result
To add or subtract minutes from Date object - use setMinutes() and getMinutes()
Now our Date object contains the UTC time
Noted that we only changed the time of our Date object. If you display the Date object, you'll still see the original timezone
Now we have the UTC time, we can convert it to any timezone
Suppose we want to convert it to Mumbai time which is +5.5 from UTC
We'll just add the destination timezone offset to the UTC time
Let's multiply 5.5 with 60 to get the offset in minutes
then add (or subtract) the offset to the UTC time. Same way as we did previously
Done! We've just successfully converted the local time to Mumbai time
This technique is quick and easy if you know the offset of destination timezone
However, if you want to convert the timezone dynamically - using the library is recommended
In our next video release, we'll talk about interesting timezone library call moment.js
Stay tune for more tips - subscribe if you like us :)