1

I'm using timestamp that is inserted into my PostreSQL database & trying to parse it to become user friendly, however I'm getting the wrong year?

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum/1000;
}
let timestamp = toTimestamp('Sun Jan 19 2020 21:19:40 GMT+0000 (Coordinated Universal Time)');

var d = new Date();
d.setTime(timestamp);

console.log(d.toGMTString()); //Mon, 19 Jan 1970 06:44:28 GMT

I'm expecting a result of Sun, 19 Jan 2020 21:19:40 GMT

1
  • Consider var d = new Date(timestamp) (once you stop dividing by 1000). Commented Jan 21, 2020 at 8:34

3 Answers 3

2

Don't divide datum by 1000

see here

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum;
}
let timestamp = toTimestamp('Sun Jan 19 2020 21:19:40 GMT+0000 (Coordinated Universal Time)');

var d = new Date();
d.setTime(timestamp);

console.log(d.toGMTString()); // Sun, 19 Jan 2020 21:19:40 GMT

Sign up to request clarification or add additional context in comments.

Comments

1

It's just a unit of measurement error. Date expects epoch in milliseconds but you are dividing the datum variable by 1000, turning it into seconds. This is resulting in the discrepancy and can be fixed by removing the divide by 1000 step.

toTimestamp then becomes:

function toTimestamp(strDate){
   return Date.parse(strDate);
}

Comments

0

use only datum instead of datum/1000 except this your code is working fine

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum;
   //return Date.parse(strDate);
}
let timestamp = toTimestamp('Sun Jan 19 2020 21:19:40 GMT+0000 (Coordinated Universal Time)');

var d = new Date();
d.setTime(timestamp);

console.log(d.toGMTString()); //Mon, 19 Jan 1970 06:44:28 GMT

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.