【发布时间】:2025-12-16 09:50:01
【问题描述】:
我想获取当前日期之后的下周一的日期。
所以如果今天的日期是 2013 年 8 月 9 日(星期五),那么我想得到 2013 年 8 月 12 日的日期。
我该怎么做?
【问题讨论】:
-
虽然这是一个简单的问题并且需要很少的努力,但日期在任何语言中都很烦人,所以我不明白为什么你应该被否决。
标签: cocoa cocoa-touch nsdate date-arithmetic
我想获取当前日期之后的下周一的日期。
所以如果今天的日期是 2013 年 8 月 9 日(星期五),那么我想得到 2013 年 8 月 12 日的日期。
我该怎么做?
【问题讨论】:
标签: cocoa cocoa-touch nsdate date-arithmetic
这段代码应该得到你想要的。它只是计算从星期一开始的天数,然后从当前日期追加。
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];
未经测试,但应该可以工作,并且无需担心更改日历的第一个日期。
而且它甚至可以轻松地添加到一周中的每隔一天,只需将9inside (9 - weekdayToday) % 7; 更改为7 + weekDayYouWant,记住那个星期天= 1,星期一 = 2...
【讨论】:
nextMonday 代码:daysToMonday = (daysToMonday == 0) ? 7 : daysToMonday;。这样,当今天是星期一时,您将添加 7 天而不是 0 天。如果您为这种情况找到更好的解决方案,请告诉我
nextDayAfterDate:matchingComponents:options: of NSCalendar。可以考虑世界各地的夏令时变化,比86400可靠得多。
您可以使用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];
类似的东西可以工作(盲打)
【讨论】: