Search code examples
javascripttimeepoch

toDateString() not working to convert a unix timestamp to human-readable format?


I'm doing this:

console.log('before:' + back[i].dateCreated);
back[i].dateCreated = new Date(back[i].dateCreated).toDateString();
console.log('after: ' + back[i].dateCreated);

And I get console logs like this:

before:1397091642
after: Fri Jan 16 1970 

But if I plug that epoc date into this conveter it comes out 4/10/2014

So does "toDateString()" not do what I think it does, or is something wrong with my timestamp or what?


Solution

  • JavaScript time is not in seconds but milliseconds. So you have to multiply by 1000:

    var epoc = 1397091642;
    var date = new Date(epoc * 1000);
    var humanReadable = date.toDateString();