简体   繁体   English

在 Swift 中,如何获取和转换 Firestore 时间戳字段

[英]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.我正在设置我的第一个 Firestore 数据库,并且我有几个日期字段存储为时间戳。 In my swift struct, the corresponding properties are declared as Date.在我的 swift 结构中,相应的属性被声明为日期。 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你的 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() :如果您需要时间戳值中的日期,请使用dateValue()

let entryDate = log.entryDate.dateValue()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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