如果截止日期實際上是今天或明天,並且顯示爲「dd-mm-yyy」,我想在標籤中顯示「Today」或「Tomorrow」其餘的格式。日期組件兩天之間的日期差異對於今天和明天是錯誤的
一切工作幾乎是完美的除了那個(因爲今天是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;
Ohh .. Now it it有道理..謝謝..有沒有什麼辦法可以比較日期而不是時間? – ZyreX
或者計算到午夜的時間以及到截止日期的時間,如果小時到午夜時間較短, – Fred
謝謝..我會嘗試 – ZyreX