2011-01-23 100 views
2

我試圖找到一個日期是星期一。iPhone - 如何檢查日期是星期一?

要做到這一點,我繼續這樣:

#define kDateAndHourUnitsComponents NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit 
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar]; 

// for test and debug purpose 
NSDateComponents* b = [calendar components:kDateAndHourUnitsComponents fromDate:retDate]; 
int a=[[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday]; 
// ----------- 

if ([[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday] == EKMonday) DoThis.... 

但是,這並不工作... a和b不包含任何有用的東西(a等於2147483647),

我也想知道是什麼可以使用[calendar components:NSWeekdayCalendarUnit fromDate:retDate]再這樣了,是沒有用在這種情況下...

我也發現了這個確認進程: How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

我錯過了什麼?

+1

在括號中使用宏定義總是一個好主意。就像這樣:'#定義kDateAndHourUnitsComponents(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)'。否則,很容易引入一些非常難以發現的問題。 – detunized

+0

OK,但這些總是用這樣的方式,而不括號 – Oliver

回答

3

這裏亞去,這通過整數工作並返回天: 7 =週六 1 =太陽 2 =週一 。 。 。

NSDate* curDate = [NSDate date]; 
int dayInt = [[[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate: curDate] weekday]; 
+0

抱歉,但是這只是在編譯時提出警告,並在運行時崩潰的應用程序,甚至後刪除空格: – Oliver

+0

對不起,我試圖記住和搞砸了我的答案。它現在是固定的,我只是把它放在一個項目中並進行驗證。 –

+1

我想知道的一件事:這是否依賴於用戶的日曆應用的「Week Starts On」設置? –

相關問題