问题描述
我想获取当前日期之后的下一个星期一的日期。
I want to get the date of the next Monday after the current date.
因此,如果今天的日期是2013-08-09(星期五),那么我想得到日期2013-08-12。
So if today's date is 2013-08-09 (Friday) then I want to get the date 2013-08-12.
我该怎么办?
推荐答案
这段代码应该可以得到您想要的。
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.
,甚至可以轻松地将其添加到一周的隔日,只需更改 9
内(9-周日今日)%7;
乘 7 + weekDayYouWant
,记住星期日= 1,星期一= 2 ...
And it can even be easily addapted to every another day of the week, just change the 9
inside (9 - weekdayToday) % 7;
by 7 + weekDayYouWant
, remembering that sunday = 1, monday = 2...
这篇关于查找下周一的NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!