我的问题的逻辑是满口的,我已经提出了解决方案。我的解决方案发布在下面。我希望看看是否有人能够提出更有效/更简单的解决方案。
该方法应该返回下一个,从现在起的未来,在给定日期的工作日发生。应在输入日期和输出日期之间保留时间。
对于所有示例,今天是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;
}
在发布解决方案之前,使用上面的输入/输出表来测试您的逻辑。
答案 0 :(得分:0)
没有理由不将逻辑放在一个循环中,因为它最多会循环两次(如果当天是星期六)。
如果当天是周末,这是一个解决方案:How to find weekday from today's date using NSDate?
- (NSInteger)isWeekend:(NSDate*)inDate
{
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:kCFCalendarUnitWeekday fromDate:inDate];
return [comp weekday];
}
然后我们可以调用此方法,检查返回的NSInteger以查看它是sat还是sun并再次运行它:
NSDate *now = [NSDate date];
now = [now dateByAddingTimeInterval:60*60*24]; // Add 1 day's worth.
NSInteger curDay = [self isWeekend:now];
while ((curDay == 6) || (curDay == 1)) // Sat or Sund.
{
now = [now dateByAddingTimeInterval:60*60*24]; // Add 1 day's worth.
curDay = [self isWeekend:now];
}
如果你真的想要删除循环,你可以检查它是否是星期六并且增加2天值,或者如果它是Sun并且增加1天值。
NSDate *now = [NSDate date];
now = [now dateByAddingTimeInterval:60*60*24]; // Add 1 day's worth.
NSInteger curDay = [self isWeekend:now];
if (curDay == 6) // Sat
{
now = [now dateByAddingTimeInterval:60*60*24*2]; // Add 2 day's worth.
}
else if (curDay == 1) // Sun
{
now = [now dateByAddingTimeInterval:60*60*24]; // Add 1 day's worth.
}