2009-12-02 59 views
0

我正在玩苹果网站上的coredatbookooks源代码示例,或者here。我试图设置书版权日期属性值来替换作为tableview部分标题的作者,并且我需要日期值为静态,这意味着我不需要时间,否则所有日期值都是不同的,并且没有两个书籍对象具有相同的日期日期和年份版权日期阵容,因为日期值的时间部分正在变化...NSDateFormatter:我不想要时间!

这里是我的RootViewController.m文件的代码,在节头用于显示日期选择日期值:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
NSString *rawDateStr = [[[fetchedResultsController sections] objectAtIndex:section] name]; 

//convert default date string to NSDate... 
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; 
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZ"]; 
NSDate *date = [formatter dateFromString:rawDateStr]; 

//convert NSDate to format we want... 
[formatter setDateFormat:@"EEEE MMMM d"]; 
NSString *formattedDateStr = [formatter stringFromDate:date]; 

return formattedDateStr; 

}

输出结果很好,但它不会让我在同一部分中将同一版权月的日期和年份分组,因为再次(我假设)日期值也有时间。从日期选择日期值的实际储蓄在EditingViewController.m文件中完成如下:

- (IBAction)save { 

// Pass current value to the edited object, then pop. 
if (editingDate) { 
    [editedObject setValue:datePicker.date forKey:editedFieldKey]; 
} 

的保存方法,目前采用的日期,从日期选择器,让我怎么修改代码首先将datepicker的日期复制到一个局部变量,并在那里消除时间,然后在setValue语句中使用该值,以便它能够正确分组?请帮忙!由于

+0

它看起来应该关闭这个问题作为一个副本或不再相关。 – 2009-12-02 18:41:44

回答

2

由于日期的固有包括时间,你就必须把它转化成其NSDateComponent S,消隐了HH:mm:ss,然后将这些过期组件回到一个NSDate修改NSDate对象本身。

例如:

NSDate * aDate = [NSDate date]; 
NSDateComponents * components = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:aDate]; 
NSDate * convertedDate = [[NSCalendar currentCalendar] dateFromComponents:components]; 

如果你这样做,你就会失去喜欢的东西时区偏移,所以你可能要考虑的是副作用。

这种方法的好处是它可以工作,不管字符串是如何格式化的(这是一个脆弱的东西来依靠)。