Search code examples
typescriptfirebasegoogle-cloud-firestoreangularfire2

How to compare date type with a timestamp saved in Firebase database?


I have a saved student presence on Firebase. With this, I have a travel screen that when starting should filter the presence that has the same date as the trip. but when I give console.log () it doesn't print anything. How can I compare the Firebase date attribute (timestamp) to a date attribute?

this.presencaSubscription = this.viagemService.carregarAlunosPorDataConfirmacao(this.data).subscribe(dados => {
      this.presencas = dados;
      console.log(this.presencas)

In the service:

carregarAlunosPorDataConfirmacao(data: Date) {
    return this.firestore.collection<Presenca>('presenca', ref => ref.where('startTime', '==', data)).snapshotChanges().pipe(
      map(dados => {
        return dados.map(snap => {
          const data = snap.payload.doc.data();
          const uid = snap.payload.doc.id;
          return { uid, ...data };
        })
      })
    )
  }

Solution

  • Firestore stores date/time values as timestamps with a microsecond precision. Unless you've taken care to store those values normalized to specific microsecond offset (which you unfortunately don't show in your question), it is unlikely that two Date values will be the exact same (which is needed for the == comparison to succeed).

    The two most common approach of dealing with dates likes this are:

    1. Store your timestamps as rounded down to a specific granularity. So if you need to select by date, you'd for example store timestamps at midnight (0:00.000) utc, and also compare against those. For start times, you'd typically round to the nearest exact minute/hour.
    2. Use range comparisons to get the property documents, so select any documents with a startTime between 2019-09-28T09:00:00.000Z and 2019-09-28T09:00:59.999Z.