In an JS app, I receive timestamp (eq. 1270544790922) from server (Ajax).
Basing on that timestamp I create Date object using:
var _date = new Date();
_date.setTime(1270544790922);
Now, _date decoded timestamp in current user locale time zone. I don’t want that.
I would like _date to convert this timestamp to current time in city of Helsinki in Europe (disregarding current time zone of the user).
How can I do that?
A Date object’s underlying value is actually in UTC. To prove this, notice that if you type
new Date(0)you’ll see something like:Wed Dec 31 1969 16:00:00 GMT-0800 (PST). 0 is treated as 0 in GMT, but.toString()method shows the local time.Big note, UTC stands for Universal time code. The current time right now in 2 different places is the same UTC, but the output can be formatted differently.
What we need here is some formatting
This works but…. you can’t really use any of the other date methods for your purposes since they describe the user’s timezone. What you want is a date object that’s related to the Helsinki timezone. Your options at this point are to use some 3rd party library (I recommend this), or hack-up the date object so you can use most of it’s methods.
Option 1 – a 3rd party like moment-timezone
This looks a lot more elegant than what we’re about to do next.
Option 2 – Hack up the date object
It still thinks it’s GMT-0700 (PDT), but if you don’t stare too hard you may be able to mistake that for a date object that’s useful for your purposes.
I conveniently skipped a part. You need to be able to define
currentHelsinkiOffset. If you can usedate.getTimezoneOffset()on the server side, or just use some if statements to describe when the time zone changes will occur, that should solve your problem.Conclusion – I think especially for this purpose you should use a date library like moment-timezone.