【发布时间】:2014-07-28 19:53:18
【问题描述】:
如果到期日实际上是今天或明天,我想在标签中显示“今天”或“明天”,其余部分以“dd-mm-yyy”格式显示。
除了以下事实(鉴于今天是 6 月 7 日)之外,一切都几乎完美无缺:
- 如果我将截止日期设置为今天(6 月 7 日)或明天(6 月 8 日),标签将更新为文本“今天”。
- 如果我将截止日期设置为后天(6 月 9 日),它会显示“明天”。
这是我的代码:
- (void)configureDueLabelForCell:(UITableViewCell *)cell withChecklistItem:(ChecklistItem *)item
{
UILabel *label = (UILabel *)[cell viewWithTag:1002];
if (item.shouldRemind) {
int difference = [self dateDiffrenceToDate:item.dueDate];
if (difference == 0) {
label.text = @"Today";
} else if (difference == 1) {
label.text = @"Tomorrow";
} else {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// [formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setDateFormat:@"dd-MM-yyyy"];
label.text = [formatter stringFromDate:item.dueDate];
}
} else {
label.text = @"";
}
}
-(int)dateDiffrenceToDate:(NSDate *)dueDate
{
// Manage Date Formation same for both dates
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSDate *startDate = [NSDate date];
NSDate *endDate = dueDate;
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
int dayDiff = [difference day];
return dayDiff;
}
我也试过了:
// NSDate *startDate = [NSDate date];
// NSDate *endDate = dueDate;
//
// NSTimeInterval secondsBetween = [endDate timeIntervalSinceDate:startDate];
//
// int numberOfDays = secondsBetween / 86400;
// NSLog(@"numberofdays: %d", numberOfDays);
//
// return numberOfDays;
【问题讨论】:
标签: ios cocoa-touch date time nsdatecomponents