2012-03-12 42 views
1

我希望能够在我的表格的标题中干净地设置我的日期。以下是我的代码:如何从NSFetchedResultsSectionInfo格式化日期?

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 
NSDate *date = [dateFormatter dateFromString:sectionInfo.name]; 
NSString *formattedDate = [dateFormatter stringFromDate:date]; 
NSLog(@"%@", formattedDate); 
return formattedDate; 
} 

使用此代码,由于日期为空,因此没有节标题出现。出于某种原因,dateFromString无法将字符串sectionInfo.name转换为NSDate。有什么建议么?

+1

你的字符串'date'格式化到什么程度? – 2012-03-12 22:21:42

+0

+1塞巴斯蒂安的问题。只是我猜他是指section的标题字符串 - sectionInfo.name的格式。如果coredata正确读取所有内容,那么唯一可能导致错误的是格式不匹配。 – makaron 2012-03-12 22:37:47

+0

嘿,我的部分标题上显示的字符串是在窗体中:2012-03-12 07:00:00 +0000我试图将其转换为2012年3月3日 – djblue2009 2012-03-12 22:56:45

回答

2

考虑到您的评论,如果您指出日期标题的格式为2012-03-12 07:00:00 +0000,则可以确定问题出现在格式设置中。

NSDateFormatterMediumStyle的格式为“1937年11月23日” - 这是你的错配:)

你必须使用这样的:从格式的字符串

[dateFormatter setDateStyle:@"yyyy-dd-MM HH:mm:ss ZZZ"]; 

,以取得一个NSDate你有。那么应该工作。

如果需要返回与NSDateFormatterMediumStyle格式的NSString,那么你得到的NSDate后,才可以将其应用到你的dateFormatter对象为你做的事:

[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 

,然后用这个dateFormatter摆脱字符串日你有:

NSString *formattedDate = [dateFormatter stringFromDate:date]; 
+0

谢谢makaron!我做了一些编辑,但关键的洞察是,为了获取一个字符串并将其转换为日期,我必须将DateFormat设置为字符串的初始格式,而不是我想要的格式。然后,它被转换成我可以操纵其格式的日期。 – djblue2009 2012-03-13 21:08:13

0

鉴于没有负载设置我的日期解析器和日期格式

@property(nonatomic, strong) NSDateFormatter *dateParser; 
@property(nonatomic, strong) NSDateFormatter *dateFormatter; 
@property(nonatomic, strong) NSDateFormatter *timeFormatter; 


- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.dateParser = [[NSDateFormatter alloc] init]; 
    self.dateFormatter = [[NSDateFormatter alloc] init]; 

    [self.dateParser setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; 
    [self.dateFormatter setDateStyle:NSDateFormatterFullStyle]; 
    ...  
} 


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
    NSDate *date = [self.dateParser dateFromString:sectionInfo.name]; 
    return [self.dateFormatter stringFromDate:date]; 
}