I had JSON with a date "date_use" :
{"expense":
{"id":1,
"amount":123.3,
"date_use":"2015-07-04T00:00:00Z"}
}
I had an error on date format when I execute this code :
self.realm!.create(Expense.self, value:json["expense"].object, update: true)
Error :
Terminating app due to uncaught exception 'RLMException', reason: 'Invalid value '2015-07-04T00:00:00Z' for property 'date_use'
My question is : What is the good date format for Realm?
The problem here is not the particular date format, but that JSON doesn't support a native date type at all. So you have to serialize dates to a string format. Using RFC 3339, like you have to deal with, is generally a good choice because it avoids ambiguities, so you can stick with that.
Realm's create method doesn't expect deserialized JSON, but a dictionary representation of your object. This expects that you have done already the preprocessing step of transforming date string representations back to Cocoa's native type NSDate. This isn't done automatically because there are date formats, which are ambiguous (unlike yours), which e.g do not provide information about the timezone.
Good news is there are excellent third-party libraries e.g. Realm-JSON, which make it a whole lot easier to deal with that. It brings built-in support for that.
This would also allow to map the property naming scheme returned by your API, e.g. date_use to names which conforms to the more broadly used camel-case dateUse.
If you don't want to introduce another dependency just for that use case, you can use and configure NSDateFormatter to parse dates conforming to your particular subset of the RFC 3339 standard, assuming they always use UTC as timezone, marked through the Z suffix.
// Setup the RFC 3339 date formatter
let rfc3339DateFormatter = NSDateFormatter()
let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX")
rfc3339DateFormatter.locale = enUSPOSIXLocale
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
rfc3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
// Convert the RFC 3339 date time string to an NSDate
var json: AnyObject! = nil
var value = json["expense"] as! [String : AnyObject]
let date: NSDate?
if let dateString = value["date_use"] as? String {
date = rfc3339DateFormatter.dateFromString(dateString)
} else {
date = nil
}
value["date_use"] = date
// Create your object
self.realm!.create(Expense.self, value: value, update: true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With