2016-01-18 84 views
0

這是我的代碼爲什麼日期始終雖然今天我傳遞不同的日期

let dateValue = formatterDate.dateFromString(request.date) 
     print("da = \(request.date)") 
     let dayValue = NSDate() 
     let compnentsDate = myCalendar.components(.Year, fromDate: dateValue!) 
     let componentsDay = myCalendar.components(.Year, fromDate: dayValue) 
     if compnentsDate.year == componentsDay.year && compnentsDate.month == componentsDay.month && compnentsDate.day == componentsDay.day { 
      cell.dateLabel.text = "today" 
     }else { 
      if compnentsDate.year == componentsDay.year && compnentsDate.month == componentsDay.month && compnentsDate.day == (componentsDay.day + 1){ 
      cell.dateLabel.text = "tomorrow" 
      }else { 
       cell.dateLabel.text = request.date 
      } 

     } 

當你看到我正在打印,並且打印的值是:

da = Jan, 25, 2016 

然而,代碼總是去第一個if語句,並告訴我「今天」

爲什麼要這樣?

我的代碼有什麼問題?

+0

NSCalendar有一個名爲isDateInToday http://stackoverflow.com/a/34441658/2303865 –

回答

5

當您調用components:fromDate:函數時,您需要指定所需的所有組件。

您需要通過.Year.Month.Day,而不僅僅是.Year。事情是這樣的:

let compnentsDate = myCalendar.components([.Year , .Month , .Day], fromDate: dateValue!) 
let componentsDay = myCalendar.components([.Year , .Month , .Day], fromDate: dayValue) 
+0

是的,它是一個數組的方法,謝謝你,它的工作 – sarah

+0

是的,這是正確的語法。 – quant24

+0

@MartinR謝謝。我只是做了一個搜索,發現了。你擊敗了我。 – rmaddy