简体   繁体   English

Javascript 中的日期解析不正确

[英]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?我正在使用插入到我的 PostreSQL 数据库中的时间戳并尝试解析它以变得用户友好,但是我得到了错误的年份?

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我期待Sun, 19 Jan 2020 21:19:40 GMT的结果

Don't divide datum by 1000不要将数据除以 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. Date 期望以毫秒为单位的纪元,但您将基准变量除以 1000,将其转换为秒。 This is resulting in the discrepancy and can be fixed by removing the divide by 1000 step.这导致了差异,可以通过删除除以 1000 步来解决。

toTimestamp then becomes: toTimestamp 然后变成:

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

use only datum instead of datum/1000 except this your code is working fine仅使用datum而不是datum/1000除了这个你的代码工作正常

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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