【发布时间】:2015-05-08 21:50:37
【问题描述】:
我的问题的逻辑是满口的,我已经想出了一个解决方案。我的解决方案发布在下面。我正在寻找是否有人可以提出更有效/更简单的解决方案。
该方法应该返回从现在开始的下一个未来,在给定日期的工作日发生。输入日期和输出日期之间应保留时间。
对于所有示例,今天是 2015 年 5 月 8 日星期五下午 4:00: 所有输入和输出都在 2015 年:
+---------------------------+---------------------------+
| Input | Output |
+---------------------------+---------------------------+
| Tuesday April 7, 3:00 PM | Monday May 11, 3:00 PM |
| Thursday May 7, 3:00 PM | Monday May 11, 3:00 PM |
| Thursday May 7, 5:00 PM | Friday May 8, 5:00 PM |
| Tuesday May 12, 3:00 PM | Wednesday May 13, 3:00 PM |
| Saturday June 20, 3:00 PM | Monday June 22, 3:00 PM |
+---------------------------+---------------------------+
这是逻辑的一些伪代码:
do {
date += 1 day;
} while(date.isWeekend || date.isInThePast)
这是我想出的解决方案,避免使用循环以保持效率:
- (NSDate *)nextWeekDayInFuture {
NSDate *now = [NSDate date];
NSDate *nextWeekDaydate;
NSCalendar *calendar = [NSCalendar currentCalendar];
nextWeekDaydate = [self dateByAddingDays:1]; // custom method, adds 1 day
if ([nextWeekDaydate isLessThan:now]) {
NSDateComponents *nowComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:now];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:nextWeekDaydate];
[nowComponents setHour:dateComponents.hour];
[nowComponents setMinute:dateComponents.minute];
[nowComponents setSecond:dateComponents.second];
nextWeekDaydate = [calendar dateFromComponents:nowComponents];
if ([nextWeekDaydate isLessThan:now]) {
nextWeekDaydate = [nextWeekDaydate dateByAddingDays:1];
}
}
NSDateComponents *components = [calendar components:NSCalendarUnitWeekday fromDate:nextWeekDaydate];
if (components.weekday == Saturday) {
nextWeekDaydate = [nextWeekDaydate dateByAddingDays:2];
} else if (components.weekday == Sunday) {
nextWeekDaydate = [nextWeekDaydate dateByAddingDays:1];
}
return nextWeekDaydate;
}
在发布解决方案之前,使用上面的输入/输出表来测试您的逻辑。
【问题讨论】:
-
4 月 7 日星期二的输入如何给出 5 月星期一的输出?为什么不是 4 月 8 日星期三?第二行也是一样 - 为什么不是 5 月 8 日星期五
-
请注意以下内容,“对于所有示例,今天是 2015 年 5 月 8 日星期五下午 4:00:所有输入和输出都在 2015 年:”。其中一项要求是从今天开始必须是将来的日期,返回的日期不能是过去的日期。
-
我投票结束这个问题,因为它属于 codereview.stackexchange.com。
-
@maddy 如果您前往stackoverflow.com/help/on-topic,您可以看到它遵守主题部分。仅仅因为它也符合相关网站上的另一个主题部分,并不意味着它不符合本网站上的内容。
标签: ios objective-c algorithm date nsdate