给定一个任意日期,我需要找到该月下一周第一天的日期。请注意,它并不像在当前日期上增加 7 天那么简单,因为该月的最后一周可能少于 7 天。这是我现在使用的代码:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSWeekOfMonthCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
NSLog(@"week of month: %ld", [components weekOfMonth]);
[components setWeekOfMonth:[components weekOfMonth] + 1];
NSLog(@"new week of month: %ld", [components weekOfMonth]); //week of month is now 2
[components setWeekday:1];
NSDate *nextWeek = [calendar dateFromComponents:components];
例如,currentDate 设置为 2012-10-01。在此示例中,nextWeek 始终为 2012-10-01。似乎发送setWeekOfMonth:
不会增加NSDateComponents
对象中的其他日期组件。我是否配置了错误的日期组件,或者setWeekOfMonth:
不应该那样工作?