How to Convert a Firestore Date/TimeStamp to a JavaScript Date – Definitive Guide

Firestore TimeStamp represents date and time as a timestamp in the UTC Epoch time.

This tutorial teaches you the different methods to convert a Firestore Date/TimeStamp to a JavaScript date.

The sample collection in the Firestore looks like the following. It consists of one Timestamp field called joinedDate.

Firestore document timestamp example

Converting Firestore TimeStamp to Date Object Using JavaScript toDate() Function

The toDate() method converts the timestamp into a JavaScript Date object.

Use this method when you want to create a Date object from the Firestore Timestamp.

  • Get the Document from your collection
  • Access the Date filed from your document. For example, joinedDate
  • Invoke the toDate() function on the object
  • It will return the Date object equivalent to the Timestamp

Code

const { Firestore } = require('@google-cloud/firestore');

// Create a new client
const firestore = new Firestore({ keyFilename: "gs-key.json" });

async function quickstart() {

  const documentRef = firestore.collection('tesat').doc('apidoccreations22');

  const snapshot = await documentRef.get();

  console.log(snapshot.data().joinedDate.toDate());

}
quickstart();

Output

2023-04-01T11:45:53.882Z

Getting the Date Alone from the Firestore TimeStamp using toDateString()

To get the date from the Timestamp

  • Convert the TimeStamp to Date using toDate()
  • Invoke the toDateString() method to get the date part alone from the Date object

Code

const { Firestore } = require('@google-cloud/firestore');

// Create a new client
const firestore = new Firestore({ keyFilename: "gs-key.json" });

async function quickstart() {

  const documentRef = firestore.collection('tesat').doc('apidoccreations22');

  const snapshot = await documentRef.get();

  console.log(snapshot.data().joinedDate.toDate().toDateString());

}
quickstart();

Output

Sat Apr 01 2023

Getting the Time Alone from the Firestore TimeStamp using toLocaleTimeString()

To get the time part alone from the Timestamp

  • Convert the TimeStamp to Date using toDate()
  • Invoke the toLocaleTimeString() method to get the locale time part alone from the Date object
const { Firestore } = require('@google-cloud/firestore');

// Create a new client
const firestore = new Firestore({ keyFilename: "gs-key.json" });

async function quickstart() {

  const documentRef = firestore.collection('tesat').doc('apidoccreations22');

  const snapshot = await documentRef.get();

  console.log(snapshot.data().joinedDate.toDate().toLocaleTimeString());

}
quickstart();
17:15:53

Additional Resources

Leave a Comment