I am looking for a function to convert date in one timezone to another.
It need two parameters,
The timezone string is described in http://en.wikipedia.org/wiki/Zone.tab
Is there an easy way to do this?
To convert a date to another time zone: Use the toLocaleString() method to get a string that represents the date according to the provided time zone. Pass the result to the Date() constructor. The returned Date object will have its date and time set according to the provided time zone.
Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
JavaScript's internal representation uses the “universal” UTC time but by the time the date/time is displayed, it has probably been localized per the timezone settings on the user's computer. And, indeed, that's the way JavaScript is set up to work.
You can't change the Date object's behavior to get it to use a different time zone just by adding or subtracting an offset. It will still use the local time zone of where it runs, for any function that requires a local time, such as . toString() and others.
Here is the one-liner:
function convertTZ(date, tzString) { return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString})); } // usage: Asia/Jakarta is GMT+7 convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time) // Resulting value is regular Date() object const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") convertedDate.getHours(); // 17 // Bonus: You can also put Date object to first arg const date = new Date() convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.
This is the MDN Reference.
Beware the caveat: function above works by relying on parsing toLocaleString result, which is string of a date formatted in en-US
locale , e.g. "4/20/2012, 5:10:30 PM"
. Each browser may not accept en-US
formatted date string to its Date constructor and it may return unexpected result (it may ignore daylight saving).
Currently all modern browser accept this format and calculates daylight saving correctly, it may not work on older browser and/or exotic browser.
side-note: It would be great if modern browser have toLocaleDate function, so we don't have to use this hacky work around.
For moment.js users, you can now use moment-timezone. Using it, your function would look something like this:
function toTimeZone(time, zone) { var format = 'YYYY/MM/DD HH:mm:ss ZZ'; return moment(time, format).tz(zone).format(format); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With