Find the NSDate for next Monday [closed]

时光怂恿深爱的人放手 提交于 2019-11-27 07:46:07

问题


I want to get the date of the next Monday after the current date.

So if today's date is 2013-08-09 (Friday) then I want to get the date 2013-08-12.

How can I do this?


回答1:


This piece of code should get what you want. It simply calculates how many days are from monday and append it from current's date.

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];

Untested, but should work, and without worrying about changing first dates of calendar.

And it can even be easily addapted to every another day of the week, just change the 9inside (9 - weekdayToday) % 7; by 7 + weekDayYouWant, remembering that sunday = 1, monday = 2...




回答2:


You can use NSCalendar method dateFromComponents: passing a properly initiated NSDateComponents object

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];

Something along these lines could work (blindly typed)



来源:https://stackoverflow.com/questions/18148224/find-the-nsdate-for-next-monday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!