查找下周一的NSDate

Cha*_*iya 7 cocoa cocoa-touch nsdate date-arithmetic

我想在当前日期之后获得下周一的日期.

因此,如果今天的日期是2013-08-09(星期五),那么我想得到2013-08-12的日期.

我怎样才能做到这一点?

Luc*_*rdo 32

这段代码应该得到你想要的.它只是计算星期一的天数,并从当前日期开始追加.

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit fromDate:now];

NSUInteger weekdayToday = [components weekday];  
NSInteger daysToMonday = (9 - weekdayToday) % 7;

NSDate *nextMonday = [now dateByAddingTimeInterval:60*60*24*daysToMonday];
Run Code Online (Sandbox Code Playgroud)

未经测试,但应该工作,而不必担心改变日历的第一个日期.

而且它甚至可以很容易地addapted到每一天的一周中,只是改变了9内部(9 - weekdayToday) % 7;7 + weekDayYouWant,记住,星期日= 1,星期一= 2 ...

  • 不适用于夏令时.有关添加日期的修改后的解决方案,请参阅此内容http://stackoverflow.com/questions/5067785/how-do-i-add-1-day-to-a-nsdate (3认同)

Vik*_*Vik 5

您可以使用NSCalendar方法dateFromComponents:传递一个正确的初始化NSDateComponents对象

NSDateComponents *components = [[NSCalendar currentCalendar] components: NSYearCalendarUnit | NSWeekOfYearCalendarUnit fromDate:[NSDate date]];

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setWeekOfYear:[components weekOfYear] + 1];
[comps setWeekday:1];
[comps setYear:[components year]];
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setFirstWeekday:2]; //This needs to be checked, which day is monday?
NSDate *date = [calendar dateFromComponents:comps];
Run Code Online (Sandbox Code Playgroud)

沿着这些方向的东西可以工作(盲目打字)

  • 工作日单位是数字1到n,其中n是一周中的天数.例如,在公历中,n为7,星期日由1表示.所以是的,可能需要更改代码 (3认同)