使用NSDateComponents计算从今天开始的下个月/第n周的日期/第n周工作日

时间:2013-03-28 19:45:32

标签: nsdatecomponents

我正在尝试计算从今天开始的日期。我想要的日期是下个月,第n周序号和从今天起的第n个工作日。我正在使用下面的代码来做到这一点。下面的代码结果是错误的。如果假设今天是2013年3月28日,我正在寻找下个月的第3个星期六的日期那么......我期待看到04/20/2013。相反,我看到04/23/2013。我无法调试此问题。请让我知道我做错了什么。谢谢你的帮助。

NSDate *todayDate = [[NSDate alloc] init]

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSYearCalendarUnit |   NSMonthCalendarUnit |NSDayCalendarUnit| NSWeekCalendarUnit | NSWeekdayOrdinalCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfYearCalendarUnit ) fromDate:todayDate];

NSUInteger todayWeekdayValue = [dateComponents weekday];   
NSUInteger todayWeekdayOrdinal = [dateComponents weekdayOrdinal];

// recurringWeekday  / recurringMonthDay get passed on  from calling function 

NSUInteger nextWeekdayValue = [self getWeekdayValueForWeekdayName:recurringWeekday];
NSUInteger nextWeekdayOrdinal = recurringMonthDay;

[dateComponentsToAdd setMonth:1];
[dateComponentsToAdd setWeekday:nextWeekdayValue - todayWeekdayValue];
[dateComponentsToAdd setWeekdayOrdinal:nextWeekdayOrdinal - todayWeekdayOrdinal];

 NSDate *nextDate = [gregorian dateByAddingComponents:dateComponentsToAdd toDate:todayDate options:0]; 

0 个答案:

没有答案