igogra
igogra

Reputation: 465

Getting incorrect dates converting timestamp with new Date

I'm trying to convert timestamp to Date but I'm getting incorrect dates. I'm working on a project with Angular and Typescript.

I have timestamps like: 1451642400 (1st january 2016) and 1454320800 (1st february 2016)

If I code:

date = new Date(1451642400);
console.log(date.toLocaleString());
date = new Date(1454320800);
console.log(date.toLocaleString());

I get: 17/1/1970 20:14:02 and 17/1/1970 20:58:40

when I should get: 1/1/2016 10:00:00 and 1/2/2016 10:00:00

What's the problem? How can I fix it?

Upvotes: 1

Views: 1348

Answers (2)

Popoi Menenet
Popoi Menenet

Reputation: 1058

The new Date()'s argument is in miliseconds. So try your timestamps with 1000 to make it in miliseconds.

var date = new Date(1451642400 * 1000);

Upvotes: 2

Rick Bronger
Rick Bronger

Reputation: 330

You need to multiply your Unix Timestamp by 1000 so its in milliseconds.. If you do it like this, it will work:

    date = new Date(1451642400 * 1000);
    console.log(date.toLocaleString());
    date = new Date(1454320800 * 1000);
    console.log(date.toLocaleString());

Upvotes: 3

Related Questions