简体   繁体   中英

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?

在此处输入图片说明

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

        ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM