Using Timestamp To Filter And Order Firestore Documents
Mon, Oct 16, 2023

Using Timestamp To Filter And Order Firestore Documents

Quick firebase cloud firestore guide on how to use timestamp to filter and order documents

Quick firebase cloud firestore guide on how to use timestamp to filter and order documents.

If you are a beginner or would want to try out the magic with cloud firestore for web, get started in this codelab here.

  • Adding a Timestamp field to your documents

The code snippet shows below how to send some "fetched" or"submitted" data to Cloud Firestore, this could be inputs from a form. We add the timestamp (time the update was done).

// Add a new document with a generated id
db.collection("devs").add({
  username: username,
  country: country,
  track: track,
  timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
  • Using Timestamp to order documents

Now let's sort and order our documents in the,"devs" collection. Let us order by timestamp and indescending order.

db.collection("devs")
  .orderBy("timestamp", "desc")
  .onSnapshot((snapshot) => {
    /_ your magic goes here _/;
  });

Congrats! Learn more about sorting and filtering data in cloud firestore in this awesome firebase doc

  • Advanced Recipe

You may want to actually at the same time format the date stored; here is how to play around with it in javascript to display for e.g 05 Jan 2019.

// Getting data (timestamp) from cloud firestore
const time = doc.data().timestamp;
const date = time.toDate();
const shortDate = date.toDateString();
const shortTime = date.toLocaleTimeString();
// Do something with dates...
console.log(shortDate);

More resources on Firebase

  • Firebase Password Authentication UI

  • Firebase Cloud Firestore Filter/Search Service

Got any question? You wanna have a chat? Hit my inbox on twitter asap 😉

  Back./Articles