要在Firebase和Swift中使用UTC-7时区保存日期,您需要执行以下几个步骤:
pod 'SwiftDate', '~> 6.0'
)。import SwiftDate
let localDate = Date() // 获取当前本地日期
let utcMinus7Zone = Region(calendar: Calendar.current, zone: TimeZone(identifier: "America/Los_Angeles")!, locale: Locale.current)
let dateInUTCMinus7 = localDate.toRegion(utcMinus7Zone).toDate()
ServerValue.timestamp()
方法将转换后的日期保存到Firebase中:import Firebase
let db = Firestore.firestore()
let data: [String: Any] = [
"date": ServerValue.timestamp(from: dateInUTCMinus7)
]
db.collection("your_collection").document("your_document").setData(data) { (error) in
if let error = error {
print("Error saving date: \(error)")
} else {
print("Date saved successfully!")
}
}
这样,您已经成功地将本地日期转换为UTC-7时区并保存到Firebase中。当您需要从Firebase检索日期时,可以使用以下代码将其转换回本地日期:
db.collection("your_collection").document("your_document").getDocument { (snapshot, error) in
if let error = error {
print("Error retrieving date: \(error)")
} else if let snapshot = snapshot, let dateValue = snapshot.get("date") as? Timestamp {
let utcMinus7Date = dateValue.dateValue().toRegion(utcMinus7Zone)
let localDate = utcMinus7Date.toRegion(Region.current).toDate()
print("Date retrieved: \(localDate)")
}
}
通过这种方式,您可以在Firebase和Swift中使用UTC-7时区来保存和检索日期。
领取专属 10元无门槛券
手把手带您无忧上云