【问题标题】:How to correctly display date time fetched from Core Data如何正确显示从 Core Data 获取的日期时间
【发布时间】:2013-05-10 06:01:11
【问题描述】:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections] objectAtIndex:section];

    //return [[[theSection name]componentsSeparatedByString:@"+"]objectAtIndex:0];

    return [NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:[theSection name]] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
}

我想使用NSDateFormatter 来显示从核心数据中获取的日期时间并根据需要显示。

更新 1

NSDateFormatter *f = [[NSDateFormatter alloc]init];
[f setDateFormat:@"dd:mm:yy hh:mm"];
NSDate *d = [f dateFromString:[theSection name]];

return [f stringFromDate:d];

这也不起作用:(

更新 2

NSLog(@"TEST=>%@",[theSection name]);

显示2013-05-09 11:58:28 +0000,但在数据库中它的存储是这样的

389773826.504289

【问题讨论】:

  • 也许您应该告诉日期所需的格式如何。如果不是,那就很难知道了
  • @pdrcabrod mm:dd:yy hh:mm:ss
  • 你使用时发生了什么:[NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:[theSection name]] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
  • @pdrcabrod 在 NSLog 中获取 (null) 并在表中获取空标题,也请查看我的问题中的更新但同样的问题。注释中的代码显示日期时间,但不是必需的格式。

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


【解决方案1】:

这应该可行:

NSDateFormatter *f = [[NSDateFormatter alloc]init];
[f setDateFormat:@"MM:dd:yy hh:mm"];

// The current section:
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.controller sections] objectAtIndex:section];
// One arbitrary object in this section:
NSManagedObject *obj = [[sectionInfo objects] objectAtIndex:0];
// The date value of this object (and all objects of this section):
NSDate *date = [obj valueForKey:@"date"]; // <-- use your "sectionNameKeyPath" here

return [f stringFromDate:date];

原因:您使用日期属性来分割表格视图。 [sectionInfo name] 将日期转换为字符串,这使得转换变得困难 日期转换为不同的格式。这种方法直接访问日期值, 并将其转换为所需的格式。

【讨论】:

【解决方案2】:
  1. 不关心格式,日期存储在数据库中。这是私人的。

  2. 假设 [section name] 返回一个字符串,您需要一个能够理解 that 格式的日期格式化程序。 (看起来像 UTC。)然后你需要一个日期格式化程序,它被设置为 output 格式。将字符串放入第一个格式化程序,取出日期,然后将日期放入第二个格式化程序。

【讨论】:

  • 您可以在我的问题中看到我已经这样做了,但问题仍然存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多