Reputation: 455
I'm developing two native apps in android and iOS (swift3) and some of my classes use Date object, but when I save a Date object from android into Firebase Realtime Database the structure is something like this:
creationDate: {
date: 3
day: 2
hours: 17
minutes: 27
month: 9
seconds: 43
time: 1507062463000
timezoneOffset: 180
year: 117
}
But this is not a common structure in iOS (by my searches off course).
What is a better solution:
Thanks
Upvotes: 3
Views: 1837
Reputation: 1543
You should use a timestamp (number of seconds since the Unix Epoch on January 1st, 1970 at UTC) :
iOS (Swift)
// Get current timestamp
let currentTimestamp = NSDate().timeIntervalSince1970
// Get date from timestamp
let date = NSDate(timeIntervalSince1970: TimeInterval(TimeInterval(yourTimestamp)))
android (Kotlin) (Take care, in android the timestamp is in milliseconds)
// Get current timestamp
val currentTimestamp = System.currentTimeMillis() / 1000 // We want timestamp in seconds
// Get date from timestamp
val date = Date(yourTimestamp * 1000) // Timestamp must be in ms to be converted to Date
Upvotes: 0
Reputation: 7668
I recommend using FIRServerValue.timestamp()
. This will ensure that a Firebase Server timestamp will be used when the data is saved to the database, that is the most accurate time because it can't be tampered by a user, and will be exactly the same across iOS and Android.
The data saved is the number of milliseconds since 1970, which you can easily convert into a date object.
For example (Swift):
myRef.setValue(FIRServerValue.timestamp())
Edit: Firebase 4
myRef.setValue(ServerValue.timestamp())
Upvotes: 4
Reputation: 3096
For iOS Use this
For saving Current time to firebase database I use Unic Epoch Conversation:
let timestamp = NSDate().timeIntervalSince1970
and For Decoding Unix Epoch time to Date().
let myTimeInterval = TimeInterval(timestamp)
let time = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))
Upvotes: 2