Reputation: 439
The string that I'm getting from the jSON return is formatted as follows: 2014-06-13T11:11:16.2
The code I'm using to store is:
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-ddTHH:mm:ss.S"];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
NSString *dateStr;
NSDate *formattedDate;
dateStr = NSLocalizedString([inventoryItem objectForKey:@"PurchaseDate"], nil);
formattedDate = [formatter dateFromString:dateStr];
newItem.purchaseDate = formattedDate;
Where am I going wrong?
Upvotes: 0
Views: 480
Reputation: 1313
Why you use NSLocalizedString?
Try use this code->
dateStr = [inventoryItem objectForKey:@"PurchaseDate"];//your formated string
Are you create new entity for "newItem"?
newItem = [NSEntityDescription insertNewObjectForEntityForName:newItemEntityName inManagedObjectContext:managedObjectContext];
And in the end are you save you changes?
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
Good luck!
Upvotes: 0
Reputation: 1622
The nil in formattedDate means that the NSDateFormatter failed to parse the string; something is wrong with the template.
In this excerpt from Apple's Date Formatter guide, they seem to put quotes around several of the items in the template string.
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
You will have to modify this to account for your 10ths of a second, here's my best guess:
[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'S"];
Upvotes: 0
Reputation: 119031
Change the format to:
@"yyyy-MM-dd'T'HH:mm:ss.S"
(you need quotes around static alpha-numeric characters in the format) Also, you might want to consider whether you want to use en_US
or en_US_POSIX
(is the date coming from a user or from the web somewhere).
Upvotes: 1