尝试在Swift中将Firebase时间戳转换为NSDate

我试图在Swift应用中使用Firebase时间戳。 我想将它们存储在我的Firebase中,并将它们用作本机NSDate对象。

文档说他们是unix时代,所以我试过了:

NSDate(timeIntervalSince1970:FirebaseServerValue.timestamp) 

没有运气。

这个:

 FirebaseServerValue.timestamp 

回报

 0x00000001199298a0 

根据debugging器。 通过这些时间戳的最好方法是什么?

ServerValue.timestamp()工作方式与在Firebase中设置普通数据的方式稍有不同。 它实际上并没有提供时间戳。 而是提供一个告诉Firebase服务器随时间填充该节点的值。 通过使用这个,你的应用程序的时间戳将全部来自Firebase,而不是用户设备发生的任何事情。

当你从观察者那里得到数值的时候,你会得到从时代开始的毫秒数。 您需要将其转换为秒来创build一个NSDate。 以下是一段代码:

 let ref = Firebase(url: "<FIREBASE HERE>") // Tell the server to set the current timestamp at this location. ref.setValue(ServerValue.timestamp()) // Read the value at the given location. It will now have the time. ref.observeEventType(.Value, withBlock: { snap in if let t = snap.value as? NSTimeInterval { // Cast the value to an NSTimeInterval // and divide by 1000 to get seconds. println(NSDate(timeIntervalSince1970: t/1000)) } }) 

你可能会发现你得到了两个非常接近的时间戳事件。 这是因为在从Firebase收到回报之前,SDK会在时间戳上采取最好的“猜测”。 一旦听到Firebase的实际价值,它将再次提高价值事件。

这个问题很老,但是我最近有同样的问题,所以我会提供一个答案。

在这里,您可以看到如何将时间戳保存到Firebase数据库

  let feed = ["userID": uid, "pathToImage": url.absoluteString, "likes": 0, "author": Auth.auth().currentUser!.displayName!, "postDescription": self.postText.text ?? "No Description", "timestamp": [".sv": "timestamp"], "postID": key] as [String: Any] let postFeed = ["\(key)" : feed] ref.child("posts").updateChildValues(postFeed) 

特别相关的代码行是"timestamp": [".sv": "timestamp"],

这将时间戳记保存为数据库中的双精度值。 这是以毫秒为单位的时间,所以您需要除以1000以获得以秒为单位的时间。 你可以在这个图像中看到一个样本时间戳。 Firebase时间戳

为了把这个double转换成Date我写了下面的函数:

 func convertTimestamp(serverTimestamp: Double) -> String { let x = serverTimestamp / 1000 let date = NSDate(timeIntervalSince1970: x) let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .medium return formatter.string(from: date as Date) } 

这给出了一个如下所示的时间戳: 时间戳

 let serverTimeStamp = ServerValue.timestamp() as! [String:Any] 

在Firebase服务器中以秒为单位进行转换之后,在Firebase存储类似[ktimeStamp:timestamp as AnyObject]时间:

 let timestampDate = NSDate(timeIntervalSince1970: Double(timestamp as! NSNumber)/1000) 

如果您使用以下方法,您将得到正确的时间:

 let timestamp = FIRServerValue.timestamp() let converted = NSDate(timeIntervalSince1970: timestamp / 1000) let dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone.localTimeZone() dateFormatter.dateFormat = "hh:mm a" let time = dateFormatter.stringFromDate(converted) 

你可以为ObjectMapper创build一个新的变换器,

 import Foundation import ObjectMapper open class FirebaseDateTransform: TransformType { public typealias Object = Date public typealias JSON = Double public init() {} open func transformFromJSON(_ value: Any?) -> Date? { if let t = value as? TimeInterval { return Date(timeIntervalSince1970: t/1000) } return nil } open func transformToJSON(_ value: Date?) -> Double? { if let date = value { return Double(date.timeIntervalSince1970) } return nil } 

要旨