I cannot convert a Firebase Timestamp to ISO format because I get this error: TypeError: thread.createdAt.toDate is not a function

Viewed 50

Inside a Firebase Cloud Function I have a thread object that has a property named createdAt. The value of that property is a Firebase Timestamp.

The thread object looks like this:

{
  "id": "h7PBcWd1aZ8KPQT36nRv",
  "message": "",
  "authorId": "q2fY5Nk4mqP1nSHN1qPFKD7NCfV2",
  "content": "eeeee",
  "ticketId": "FvqhdvSvLGlG7I3Nn9v7",
  "uploadToSupport": true,
  "createdAt": {
    "_nanoseconds": 938000000,
    "_seconds": 1662693778
}

Now I want to convert the createdAt Firebase Timestamp into ISO Format so I can use it with an external 3rd party API. For example: 2018-09-10T11:54:03.000Z.

I am trying to convert it using the Firebase toDate method, like this:

const createdTime = thread.createdAt.toDate().toISOString();

But when I run the Cloud Function it throws an error saying:

TypeError: thread.createdAt.toDate is not a function

1 Answers

Date() uses milliseconds to convert to a date string. You must convert seconds and nanoseconds to milliseconds and sum them, then convert to a date

let docData = {
  "createdAt": {
    "_nanoseconds": 938000000,
    "_seconds": 1662693778
  }
}

//since Date() uses milliseconds, convert nanoseconds and seconds to millis, then use toLocaleString()
let dateString = new Date(docData.createdAt._seconds * 1000 + docData.createdAt._nanoseconds/1000000).toLocaleString(); 

console.log(dateString);

Related