Rohit
Rohit

Reputation: 2326

Pass and filter items by TimeStamp in Firestore for Swift

I am trying to pass today's date in Firestore Timestamp in my app. I am getting the today's date like this

formatter.dateFormat = "MMMM d, yyyy"
let result = formatter.string(from: date)
print("Today date is \(result)")
let startDate = result + " " + "07:00:00"
let endDate = result + " " + "23:00:00"

I have to pass the today's date from morning 7 am to 23:00 pm and I stored this dates in startDate and endDate. Now I am passing these timing in Firestore query like this:-

self.db.collection("Locations").whereField("userid", isEqualTo: "\(selectedUserID)").whereField("createddatetime", isGreaterThanOrEqualTo: "\(startDate)").whereField("createddatetime", isLessThanOrEqualTo: "\(endDate)").getDocuments()

but I am getting no results in my snapshot. How can I do this. Please help?

enter image description here

Upvotes: 5

Views: 3419

Answers (1)

maxwell
maxwell

Reputation: 4156

You need:

1) Convert String -> Date

2) Convert Date -> Timestamp (FIRTimestamp)

formatter.dateFormat = "MMMM d, yyyy HH:mm:ss"

let startTime: Date = formatter.date(from: startDate) ?? Date(timeIntervalSince1970: 0)
let startTimestamp: Timestamp = Timestamp(date: startTime)

let endTime: Date = formatter.date(from: endDate) ?? Date()
let endTimestamp: Timestamp = Timestamp(date: endTime)

3) Change func to:

self.db.collection("Locations")
        .whereField("userid", isEqualTo: "\(selectedUserID)")
        .whereField("createddatetime", isGreaterThanOrEqualTo: startTimestamp)
        .whereField("createddatetime", isLessThanOrEqualTo: endTimestamp)
        .getDocuments() { (snapshot, error) in

        ...

}

Upvotes: 10

Related Questions