/ javascript

Formatting Unix Timestamp in Javascript

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 GMT +8.

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.

Example:

  • 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.

Example:

  • offset in SG: -480 (result of getTimezoneOffset in minutes)
  • 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.

Example:

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 😄.

Formatting Unix Timestamp in Javascript
Share this