如何使用swift 4将Firebase ServerValue.timestamp()转换为日期或毫秒
这里,我想将时间戳转换为毫秒,但无法转换。请提供帮助。按如下方式扩展Date类以从时间戳转换为日期:如何使用swift 4将Firebase ServerValue.timestamp()转换为日期或毫秒,swift,firebase,date,firebase-realtime-database,milliseconds,Swift,Firebase,Date,Firebase Realtime Database,Milliseconds,这里,我想将时间戳转换为毫秒,但无法转换。请提供帮助。按如下方式扩展Date类以从时间戳转换为日期: extension Date { var millisecondsSince1970:Int { return Int((self.timeIntervalSince1970 * 1000.0).rounded()) } init(milliseconds:Int) { self = Date(timeIntervalSince1970:
extension Date {
var millisecondsSince1970:Int {
return Int((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds:Int) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
}
}
在从firebase获取后,您可以将时间戳转换为日期
let date = Date.init(milliseconds:object.startDate!)
最后,我找到了答案 步骤1:添加Pod依赖项 第二步: 创建类型为TransformType的FirebaseDateTransform类,并重写函数transformFromJSON(…) 第三步: 将日期转换为毫秒的扩展名
我问的是如何将Firebase Servalue.timestamp()转换为数据或转换为毫秒以转换为简单数据。回答之前请先阅读问题。是的,jazzbpn,我想我误解了,映射是你在回答中已经写过的方式。另一方面,使用
ServerValue.timestamp()。我使用它就像let node=[“item”:“value”,“timestamp”:ServerValue.timestamp()]
。顺便说一句,感谢您提供的解决方案:)这似乎太复杂了,无法只获取/设置一个简单的值。
// Created by Bipin on 9/26/18.
// Copyright © 2018 profyl.org. All rights reserved.
//
import Foundation
import ObjectMapper
import Firebase
enum FirebaseDate {
case date(Date)
case serverTimestamp
var date: Date {
switch self {
case .date(let date):
return date
case .serverTimestamp:
return Date()
}
}
}
class FirebaseDateTransform: TransformType {
public typealias Object = FirebaseDate
public typealias JSON = Any
open func transformFromJSON(_ value: Any?) -> FirebaseDate? {
switch value {
case is [AnyHashable: Any]?:
return .serverTimestamp
default:
return nil
}
}
open func transformToJSON(_ value: FirebaseDate?) -> Any? {
switch value {
case .serverTimestamp?:
return ServerValue.timestamp()
default:
return nil
}
}
open func getFirebaseTimestamp()->String{
return String(transformFromJSON(ServerValue.timestamp())!.date.toMillis())
}
}
extension Date {
func toMillis() -> Int64! {
return Int64(self.timeIntervalSince1970 * 1000)
}
}