简体   繁体   English

无法在 Javascript 中正确地将时间戳转换为日期

[英]Can't convert timestamp to date properly in Javascript

I use mongodb as my database and in that db I have a timestamp field but I haven't seen any format similar to that.我使用 mongodb 作为我的数据库,在那个数据库中我有一个时间戳字段,但我没有看到任何类似的格式。 Some of them are:他们之中有一些是:

1657479170.7300725
1657479170.7301126
1657479170.7301197
1657479170.9120467
1657479170.932398

When i try to convert this to normal date format (YYYY-MM-DD) I get the correct date.当我尝试将其转换为正常日期格式(YYYY-MM-DD)时,我得到了正确的日期。 For example the converted date of the first timestamp above is:例如上面第一个时间戳的转换日期是:

10.07.2022 21:52:50

However when I try to convert it in javascript I get:但是,当我尝试在 javascript 中转换它时,我得到:

1970-01-20 06:24:39

which is definitely not correct value.这绝对不是正确的值。

My code for the conversion :我的转换代码:

ConvH.forEach(conv => {
    conv.tracker.events.forEach(element => {
        console.log(parseFloat( parseFloat(element.timestamp.toFixed(4))),  moment(new Date( parseFloat( element.timestamp.toFixed(4)))).format("YYYY-MM-DD HH:mm:ss"));
        element.timestamp = new Date(element.timestamp).toLocaleString();
        
    })
});

Note : new Date(element.timestamp).toLocaleString();注意:new Date(element.timestamp).toLocaleString(); gives the same thing :/给出相同的东西:/

试试这个: new Date(timestamp.getHighBits() * 1000)

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

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