ctz
ctz

Reputation: 5

react.js wrong resuilt when converting timestamp to date

I am trying to convert a UNIX timestamp to date in react.js. It works well but the only thing is that I get the wrong year. I just can't understand why it happens. I think it is probably the problem with my computer or other things but I just can't figure it out.

Here is my log in to the browser.

Object { seconds: 1620198000, nanoseconds: 0 }  // The timestamp value
Date Sat May 05 3990 00:00:00 GMT-0700         // The converted date

And also my code here

const date= new Date(unixTimestamp * 1000)
return (
    <p>{date.toTimeString()}</p>   // Getting 3990/5/5 instead of 2021/5/5
)

Upvotes: 0

Views: 531

Answers (1)

Wt.N
Wt.N

Reputation: 1658

Your timestamp is firebase.firestore.Timestamp, isn't it? You can

timestamp.toDate()

to get Date object.

By the way, how did you get unixTImestamp? new Date(1620198000 * 1000) returns correct timestamp, Wed May 05 2021 16:00:00 GMT+0900 (Japan Standard Time)

I assume you new Date(timestamp.seconds * 1000) will give you the expected result.

https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp#todate

Upvotes: 1

Related Questions