Search code examples
iosobjective-ccore-datansdatensdateformatter

Store NSDate in CoreData


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?


Solution

  • 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).