Home > OS >  How to query data that has a timestamp that is less than n hours?
How to query data that has a timestamp that is less than n hours?

Time:10-13

Currently my method for determining wether data is older than n hours uses this code after getting a timestamp from a document:

let timestamp = i.get("timestamp") as! Timestamp
                
                let lastUpdatedDate = timestamp.dateValue()

                let currentDate = Date()

                let cal = Calendar.current
                let components = cal.dateComponents([.hour], from: lastUpdatedDate, to: currentDate)
                let diff = components.hour!

Usually this code is executed in a for each loop per each document after getting the documents from firestore.

Is there a way to query data using the field timestamp and checking if it is less than n hours instead?

ref.collection("References").whereField("timestamp", isLessThanOrEqualTo: n hours)

CodePudding user response:

If you want a value to compare it against, you can do:

let date = Date().addingTimeInterval(-4 * 60 * 60)

Or you can do:

let date = Calendar.current.date(byAdding: .hour, value: -4, to: Date())

You may have to convert those to a Timestamp from this Date object, e.g., presumably something like:

let timestamp = Timestamp(date)
  • Related