love
love

Reputation: 21

How can I serverTimeStamp to Date?

  const docRef = await addDoc(collection(db, "question"), {
    title: writingTitle,
    createdAt: serverTimestamp(),
  });

If you write servertimestamp() when you write, the console window says {seconds=123123123, nanosecond=!@!@}} like this. How can I change this to Date on the web?

Upvotes: 2

Views: 2564

Answers (2)

clauziere
clauziere

Reputation: 1342

Here's how I do it (with Typescript / React Native):

  const docRef = await addDoc(collection(db, "question"), {
    title: writingTitle,
    createdAt: serverTimestamp(),
  });
  const docSnapshot = await docRef.get();
  //Then get any data from the added object
  const timestamp = docSnapshot.data().createdAt

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 600130

To convert a Firestore timestamp to a date, call toDate() on it after reading the value from the database. For more on this, see the reference docs.

There is no way to get the value before that/without reading it, as serverTimestamp() only generates a token value/sentinel that the database server recognizes as a signal to write the date/time.

Upvotes: 1

Related Questions