0

In my chat app(using firebase) I used to store time stamps of messages like this

msg = {
  // ...
  timestamp: serverTimestamp(),
};

When the msg document was retrieved and parsed into javascript date object

const date = new Date(timestamp * 1000);
const year = date.getFullYear();

The getFullYear() method returns 3991 instead of 2022

could anyone help me to fix this ?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 3
    `timestamp * 1000` might be the issue? – evolutionxbox Aug 15 '22 at 12:57
  • 2
    Yep, why is it being multiplied by 1000? – Irfanullah Jan Aug 15 '22 at 12:58
  • 3
    What actual value does `serverTimestamp()` deliver? – KooiInc Aug 15 '22 at 13:22
  • Yup, check that `serverTimestamp()` - I'm assuming it's dropping the leading `1` or `16` – Charly Aug 15 '22 at 13:31
  • sorry this question already has an answer [here](https://stackoverflow.com/questions/38016168/how-to-convert-firebase-timestamp-into-date-and-time) – Harshavardhan Aug 15 '22 at 13:41
  • @evolutionxbox I don't know how to deal with date objects i was told that UTC time formats must be multiplied by 1000. But firebase timestamp has an inbuilt method `toDate()` to convert from UTC to local date – Harshavardhan Aug 15 '22 at 13:45
  • Depends on the value of the timestamp. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#parameters the timestamp should be the number of _milliseconds_ since the UNIX epoch. – evolutionxbox Aug 15 '22 at 13:48
  • @Harshavardhan—that doesn't seem to be correct. `new Date(new Date(3991, 0)/1000).getFullYear()` returns 1972, not 2022. Conversely, `new Date(Date.now() * 1000).getFullYear()` returns 54594, not 3991. – RobG Aug 16 '22 at 15:10

0 Answers0