2013-05-10 78 views
-2
- (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 
+1

也许你应该告诉日期的格式。如果没有,它很难知道 – pdrcabrod 2013-05-10 06:17:39

+0

@pdrcabrod mm:dd:yy hh:mm:ss – 2013-05-10 06:27:02

+0

当你使用:[NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:[theSection name]] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];' ? – 2013-05-10 06:28:20

回答

3

这应该工作:

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] 将日期转换为字符串,这使得难以将日期转换为不同的格式。该方法直接访问日期值,并将其转换为所需的格式。

+1

@ S.J。马丁的方法是正确的。这与我的一个(见http://stackoverflow.com/questions/16070597/doubts-on-concurrency-with-objects-that-c​​an-be-used-multiple-times-like-formatte)允许你提高性能; )。格式化器创建起来很昂贵。 +1一如既往,Martin – 2013-05-10 08:11:12

+0

@MartinR非常感谢你的帮助:),这个工作非常出色。 – 2013-05-10 10:28:55

+0

@MartinR请同时查看这个问题http://stackoverflow.com/questions/16482239/why-nspredicate-not-working – 2013-05-10 12:27:23

0
  1. 不关心格式,日期存储在数据库中。这是私人的。

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

+0

你可以在我的问题中看到我已经做到了,但问题仍然存在。 – 2013-05-10 07:49:04

相关问题