2015-10-23 173 views
0

我想獲得本月的第一個星期二。我這樣做:月的第一個星期二

NSDate *today = [NSDate date]; 

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
NSDateComponents *com = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfMonth|NSCalendarUnitDay|kCFCalendarUnitWeekday|NSCalendarUnitWeekdayOrdinal fromDate:today]; 
[com setWeekday:3]; 
[com setWeekdayOrdinal:1]; 

NSDate *firstTuesday = [calendar dateFromComponents:com]; 
NSLog(@"firstTuesday %@", firstTuesday);// firstTuesday 2015-10-22 22:00:00 +0000 

你知道我在做什麼錯嗎?由於

+0

這不是一回事。第一個是「測試一個日期是否是該月的第一個星期二」第二個問題是「如何獲得該月的第一個星期二作爲NSDate」 – samir

+0

道歉;誤讀了。 – trojanfoe

+0

好的沒問題。謝謝 – samir

回答

0

最後我得到它,這是示例代碼:

NSDate *today = [NSDate date]; 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
NSDateComponents *todayCompoenents = [calendar components:NSCalendarUnitYear |NSCalendarUnitMonth fromDate:today]; 

NSDateComponents *com = [[NSDateComponents alloc] init]; 

[com setYear:[todayCompoenents year]]; 
[com setMonth:[todayCompoenents month]]; 
[com setWeekday:3]; 
[com setWeekdayOrdinal:1]; 

NSDate *firstTusday = [calendar dateFromComponents:com]; 
NSLog(@"firstTusday %@", firstTusday); 
相關問題