Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to convert Firebase timestamp to NSDate in Swift

Tags:

I'm trying to use Firebase timestamps in a Swift app. I'd like to store them in my Firebase, and use them as native NSDate objects in my app.

The docs say they are unix epoch time, so I've tried:

NSDate(timeIntervalSince1970:FirebaseServerValue.timestamp) 

with no luck.

This:

FirebaseServerValue.timestamp 

returns

0x00000001199298a0 

according to the debugger. What is the best way to pass these timestamps around?

like image 641
Fook Avatar asked Mar 24 '15 21:03

Fook


1 Answers

ServerValue.timestamp() works a little differently than setting normal data in Firebase. It does not actually provide a timestamp. Instead, it provides a value which tells the Firebase server to fill in that node with the time. By using this, your app's timestamps will all come from one source, Firebase, instead of whatever the user's device happens to say.

When you get the value back (from a observer), you'll get the time as milliseconds since the epoch. You'll need to convert it to seconds to create an NSDate. Here's a snippet of code:

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))     } }) 

You may find that you get two events raised with very close timestamps. This is because the SDK will take a best "guess" at the timestamp before it hears back from Firebase. Once it hears the actual value from Firebase, it will raise the Value event again.

like image 149
katfang Avatar answered Oct 31 '22 01:10

katfang