如果截止日期实际上是今天或明天,我想在标签中显示"Today"或"Tomorrow",其余的则以"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;
From https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html#//apple_ref/doc/uid/TP40007836-SW1
"……此方法将计算结果截断到所提供的最小单位。例如,fromDate:参数对应于2010年1月14日11:30 PM, toDate:参数对应于2010年1月15日8:00 AM,那么这两个日期之间只有8.5小时。如果你问的是天数,你得到0,因为8.5小时小于1天。在某些情况下,这应该是1天。您必须确定在特定情况下用户期望的行为。如果您确实需要一个返回天数的计算,通过两个日期之间的午夜数来计算,那么您可以使用类似于清单13中的NSCalendar类别。"