Date class converts Timestamp wrong

In my application, I am creating a live console where I output messages with their timestamp and contents. From what I read, the approach I am using below with the Date() class should work as expected, where the timestamp is multiplied by 1000 to get the milliseconds.

I am logging the timestamp for debugging purposes and getting values like "1441041070066". When I plug these into the Epoch/Unix Converters, the date/time is correct. My code however is giving my nonsense like "22:7:46" and then 1 minute later "20:48:37". Can anyone please explain what it is that I am doing wrong in this case?

messages.forEach( function (item)
{
    var timestamp = item.Timestamp; // /Date(1440823073243)/
    var timestamp = timestamp.substring(timestamp.lastIndexOf("(")+1, timestamp.lastIndexOf(")"));

    console.log(timestamp);

    var source = item.Source;
    var type = item.Type;
    var contents = item.Contents;

    // Get Date/Time in Milliseconds
    var date = new Date(timestamp * 1000);
    var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

    console_log("<font color='blue'>" + time + "</font>" + ": " + contents);
});
Jon Skeet
people
quotationmark

The timestamp you've got is already in milliseconds. I don't know which converter you used, but if you put 1440823073243 into epochconverter.com it shows:

Assuming that this timestamp is in milliseconds

... and comes up with a timestamp of GMT: Sat, 29 Aug 2015 04:37:53 GMT.

So basically you should remove the * 1000 part of your code, but parse timestamp (which is still a string) into a number:

var date = new Date(parseInt(timestamp));

Additionally, you should use alternative ways of formatting your date:

  • You're currently using the users's time zone; it's not clear whether that's what you want or not. (It may well be, but you should think about it.)
  • By just using string concatenation, you won't get any padding, leading to strings like "22:7:46".

Basically, research alternative formatting options - whether as part of the Javascript standard libraries, or with something like moment.js.

people

See more on this question at Stackoverflow