【问题标题】:Store NSDate in CoreData将 NSDate 存储在 CoreData 中
【发布时间】:2014-06-19 18:48:41
【问题描述】:

我从 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;

我哪里错了?

【问题讨论】:

  • 这段代码给你什么结果?格式化日期为零吗?如果您记录 dateStr,它是您在第一句话中显示的格式吗?
  • dateStr - 2014-06-05T13:43:45.03 formattedDate - (null)
  • 您好。我们宁愿你不签署你的帖子,添加问候,或添加感谢和未来的赞赏。如果可以的话,让你的问题保持简洁——这通常是它们的编辑方式,理想情况下。

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


【解决方案1】:

将格式改为:

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

(您需要在格式中为静态字母数字字符加上引号)另外,您可能需要考虑是否要使用en_USen_US_POSIX(是来自用户或来自某处的网络的日期) .

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      你为什么使用 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();
          } 
      }
      

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多