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?
If the format isn't super important and you don't want import some big library you could just use Intl.DateTimeFormat to convert Date objects to different timezones.
Offsets, daylight saving, and other diff changed in the past will be taken care of for you
You can experiment with the language to get other literals.
Here is my code, it is working perfectly, you can try with give below demo:
You can also use https://www.npmjs.com/package/ctoc_timezone
It has got much simple implementation and format customisation.
Changing format in toTimeZone:
CtoC.toTimeZone(new Date(),"EST","Do MMM YYYY hh:mm:ss #{EST}");
Output :
28th Feb 2013 19:00:00 EST
You can explore multiple functionalities in the doc.
If you just need to convert timezones I have uploaded a stripped-down version of moment-timezone with just the bare minimum functionallity. Its ~1KB + data:
For moment.js users, you can now use moment-timezone. Using it, your function would look something like this:
I was having trouble using Moment Timezone. I am adding this answer just so if somebody else faces the same issue. So I have a date string
2018-06-14 13:51:00
coming from myAPI
. I know that this is stored inUTC
but the string doesn't speak for itself.I let moment timezone know, what timezone this date is from by doing:
Now I would like to convert it to a specific timezone by doing: