Say you have a Unix timestamp that is returned by the server, and you need to format it into human readable date.
Doing this is wrong:
var ts = 1469980800; var d = new Date(ts * 1000);
This is because this will return a different date depending on which timezone the user's computer is set in. So a person in
GMT 0 will be looking at a different date from another person in
Awful. You don't want to create that kind of confusion.
Rule number 1: You will have to deal with
getTimezoneOffset() regardless of the timezone your Unix timestamp is in.
- timestamp: 1469980800 (1 AUG 00:00:00 in Singapore)
Rule number 2: Get user's
timezoneoffset and subtract that with the timezone your timestamp is in.
- offset in SG: -480 (result of
- offset in JAP: -540 (result of 'getTimezoneOffset' in minutes)
So the difference between the user's timezone setting and your timestamp's timezone is
-540 - (-480) = -60.
Finally: Add the difference to your timestamp.
var ts = 1469980800; var diff = -60; var final = ts + (diff * 60); // remember diff is in minutes var d = new Date(final * 1000); // remember JS processes timestamp in microseconds level console.log(d.getDate () + '.' + (d.getMonth () + 1) + '.' + d.getFullYear () + ' ' + d.getHours () + ':' + d.getMinutes () + ':' + d.getSeconds ());
You should be getting this:
1.8.2016 0:0:0 regardless of which timezone setting your computer is set to. Hopefully 😄.