将NSDate存储在CoreData中

时间:2014-06-19 18:48:41

标签: ios objective-c core-data nsdate nsdateformatter

我从jSON返回获得的字符串格式如下:2014-06-13T11:11:16.2

我用来存储的代码是:

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;

我哪里错了?

3 个答案:

答案 0 :(得分:1)

将格式更改为:

@"yyyy-MM-dd'T'HH:mm:ss.S"

(您需要使用格式中的静态字母数字字符引用)此外,您可能还想考虑是否要使用en_USen_US_POSIX(来自用户或来自网络某处)。

答案 1 :(得分:0)

formattedDate中的nil表示NSDateFormatter无法解析字符串;模板有问题。

在Apple的Date Formatter指南的摘录中,他们似乎在模板字符串中的几个项目周围加上了引号。

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];

你必须修改这个以计算你的十分之一秒,这是我最好的猜测:

[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'S"];

答案 2 :(得分:0)

为什么使用NSLocalizedString?

尝试使用此代码 - >

dateStr = [inventoryItem objectForKey:@"PurchaseDate"];//your formated string

您是否为“newItem”创建新实体?

newItem = [NSEntityDescription insertNewObjectForEntityForName:newItemEntityName inManagedObjectContext:managedObjectContext];

最后你能保存更改吗?

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();
    } 
}
祝你好运!