Skip to content
Advertisement

How to convert Firestore Timestamp to Date() – Firestore V9

Before updating to V9, I use this:

let data = doc.data();

for (let field in data) {
    let value = data[field];

    // If value is an instance of Timestamp, convert it to javascript Date()
    if (value instanceof firebase.firestore.Timestamp) {
        data[field] = value.toDate();
    }
}

But now, after updating to V9, I run into 2 problems, and the documentation mentions nothing about Timestamp for javascript SDK:

  1. firebase.firestore.Timestamp is no longer available to use to check if a field is a Timestamp Object.
  2. None of the field has the “toDate()” function any more.

So my questions are, with the javascript V9 SDK:

  1. How do I check if a field is an instance of Timestamp?
  2. How do I convert an instance of Timestamp into Date() object?

Advertisement

Answer

How do I check if a field is an instance of Timestamp?

You can import Timestamp class from Firestore package.

How do I convert an instance of Timestamp into Date() object?

This method exists on a Timestamp object.

import { Timestamp } from "firebase/firestore"

const timeObj = new Timestamp();

console.log(timeObj instanceof Timestamp)
console.log(timeObj.toDate());
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement