本月的第一个星期二

时间:2015-10-23 08:16:45

标签: objective-c nsdate

我想获得本月的第一个星期二。我这样做:

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

你知道我做错了什么吗?感谢

1 个答案:

答案 0 :(得分: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);