简体   繁体   中英

Date not parsing correct in Javascript

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

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

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM