[英]Store NSDate in CoreData
我從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;
我要去哪里錯了?
將格式更改為:
@"yyyy-MM-dd'T'HH:mm:ss.S"
(您需要在格式中的靜態字母數字字符周圍加上雙引號)此外,您可能要考慮要使用en_US
還是en_US_POSIX
(日期是來自用戶還是來自網絡的某個日期)。
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"];
為什么使用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();
}
}
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.