2014-06-07 53 views
2

如果截止日期實際上是今天或明天,並且顯示爲「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; 

回答

3

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,並且toDate:參數對應於2010年1月15日的8 :上午00時,兩個日期之間只有8.5小時。如果你問天數,你會得到0,因爲8.5小時小於1天。可能有這種情況應該是1天。您必須決定您的用戶在特定情況下期望的行爲。如果您確實需要計算返回兩天之間的夜間數計算的天數,則可以使用類似於清單13中類似的NSCalendar。「

+0

Ohh .. Now it it有道理..謝謝..有沒有什麼辦法可以比較日期而不是時間? – ZyreX

+0

或者計算到午夜的時間以及到截止日期的時間,如果小時到午夜時間較短, – Fred

+0

謝謝..我會嘗試 – ZyreX