0
votes

I have Core Data and one of my entity property is object of type Date (i assume it is NSDate). From JSON response i got date in following format:2016-01-09 22:33:33

When mapping, i'm setting values in my NSManagedObject like that:

 [item setValue:[obj valueForKey:JS_DATE] forKey:CD_DATE];

Where macros are simply string, referring to entity name or json response key for date.

App throw an exception on that, i assume i want to save NSDate with different format. How to fix that?

Thanks.

1
Use NSDateFormatter to transform the NSString object into NSDate one, or change the property type to NSString, but you may loose some good feature for predicates with NSDate (like <, =<, > or >=).Larme

1 Answers

0
votes

Try something along the lines of

// Setup formatter
myDateFormatter = [[NSDateFormatter alloc] init];
myDateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
myDateFormatter.dateFormat = @"yyyy-MM-dd' 'HH:mm:ss";
myDateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

// Use it
NSString *stringFromJSON = @"2016-01-09 22:33:33";
NSDate *date = [myDateFormatter dateFromString:stringFromJSON];

// Validate Date
NSLog(@"Date: %@, date);

You probably have to experiment with locale and timeZone, depending on where you live. Have a look at that tech note for hints: https://developer.apple.com/library/content/qa/qa1480/_index.html