I am looking for a function to convert date in one timezone to another.
It need two parameters,
- date (in format "2012/04/10 10:10:30 +0000")
- timezone string ("Asia/Jakarta")
The timezone string is described in http://en.wikipedia.org/wiki/Zone.tab
Is there an easy way to do this?
Having looked around a lot including links from this page i found this great article, using moment timezone:
https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/
To summarise it:
Get the user's timezone
Returns eg: Timezone: Europe/London
Set the default user timezone
Set custom timezone
Convert date / time to local timezone, assumes original date/time is in UTC
Returns: Sun, 25th December 2016, 7:00am
Convert date/time to LA Time
Returns: Sat, 24th December 2016, 11:00pm
Convert from LA time to London
Returns: Sun, 25th December 2016, 3:00pm
Got it !
Wanted to force the date shown = server date, no mattter the local settings (UTC).
My server is GMT-6 --> new Date().getTimezoneOffset() = 360.
Okay, found it!
I'm using timezone-js. this is the code:
I should note that I am restricted with respect to which external libraries that I can use. moment.js and timezone-js were NOT an option for me.
The js date object that I have is in UTC. I needed to get the date AND time from this date in a specific timezone('America/Chicago' in my case).
UTC is currently 6 hours ahead of 'America/Chicago'. Output is:
People familiar with the java 8
java.time
package, orjoda-time
will probably love the new kid on the block: the js-joda library.Install
Example
In true java nature, it's pretty verbose lol. But, being a ported java library, especially considering they ported 1800'ish test cases, it also probably works superbly accurately.
Chrono manipulation is hard. That's why many other libraries are buggy in edge cases. Moment.js seems to get timezones right, but the other js libs I've seen, including
timezone-js
, don't seem trustworthy.Time Zone Offset for your current timezone
For my GMT+10 timezone (Australia) it returned -36000