简体   繁体   中英

in Swift, how to fetch and convert Firestore timestamp field

I'm setting up my first Firestore database and I have several date fields stored as timestamps. In my swift struct, the corresponding properties are declared as Date. First question - is that the correct way to do it? if so, how do I fetch those timestamp values? I've been trying to find the solution but it does not seem to be obvious solution.

struct HealthLog1: Codable {
   var comment: String?
   var entryDate: Date?
   var familyMemberID: String?
   var logID: String?
   var user_ID: String?
 }



 db.collection("healthLogs").whereField("familyMemberID", isEqualTo: person.familyMemberID!).getDocuments { (snapshot, error) in
        
        if error == nil && snapshot != nil {
            
            for doc in snapshot!.documents {
                
                let log = HealthLog1(
                    comment: doc["comment"] as? String,
                    entryDate: doc["entryDate"] as? Date,
                    familyMemberID: doc["familyMemberID"] as? String,
                    logID: doc["logID"] as? String,
                    user_ID: doc["user_ID"] as? String)
   
                healthLogs.append(log)

            }
            
            self.delegateHLP?.receiveLogs(healthLogs: healthLogs)
        }
        else {
            print ("there is some error with the get documents")
        }
    }
}

Declare date as a Timestamp.

Your model

class HealthLog1: Codable {
    var comment: String?
    var entryDate: Timestamp? //<-- Declare Timestamp
    var familyMemberID: String?
    var logID: String?
    var user_ID: String?
}

Init

let log = HealthLog1(
    comment: doc["comment"] as? String,
    entryDate: doc["entryDate"] as? Timestamp,
    familyMemberID: doc["familyMemberID"] as? String,
    logID: doc["logID"] as? String,
    user_ID: doc["user_ID"] as? String)

If you need date from Timestamp value then use dateValue() :

let entryDate = log.entryDate.dateValue()

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