Home > Net >  Can't convert timestamp to date properly in Javascript
Can't convert timestamp to date properly in Javascript

Time:07-19

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. 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. 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:

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(); gives the same thing :/

CodePudding user response:

Try this: new Date(timestamp.getHighBits() * 1000)

  • Related