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?
This question is old, but I recently had the same problem so I'll provide an answer.
Here you can see how I am saving a timestamp to Firebase Database
The particularly relevant line of code is
"timestamp": [".sv": "timestamp"],
This saves the timestamp as a double in your database. This is the time in milliseconds so you need to divide by 1000 in order to get the time in seconds. You can see a sample timestamp in this image.
To convert this double into a Date I wrote the following function:
This gives a timestamp that looks like this:
You can create a new transformer for ObjectMapper,
Gist
Swift 4 and updated Firebase library variation of Katfang's answer:
Store in
Firebase
something like[ktimeStamp:timestamp as AnyObject]
than after you convert in seconds using Firebase Server Time:Here is some code, based on alicanbatur's answer, that allows a date to be a Double or a server timestamp, and yet still work within an object mapping layer such as ObjectMapper.
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:
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.