算出时间跨度是否大于24小时



我不知道我是不是疯了,或者这是否可能。

顺便说一下,我没有使用任何标准库,所以这不是语言依赖的,因此为什么它在这里而不是在stackoverflow上。

我有两个以int格式传递给我的时间段。

1st period-
    Start Time:
    End Time:
2nd period-
    Start Time:
    End Time:

Int是从午夜开始的分钟数,所以7am是420分钟。

我想写的一个函数的例子是:

bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime,
                         int secondStartTime, int secondEndTime)
{
    ....
}

我甚至不确定这能不能做到。

注:跨越午夜是可以的,但也不一定。句点不能重叠

So it could look like this:
420, 1140, 1260, 419
7am, 7pm,  9pm,  6:59am
- Valid
This would be valid since it doesn't span over 24 hours.
420, 1140, 1260, 421
7am, 7pm,  9pm,  7:01am
- Not valid
420, 60, 120, 419
7am, 1am,2am, 6:59am
- Valid

我必须确保从第一节课开始时间到第二节课结束时间不超过24小时。

如果一个周期可以从星期一开始到星期三结束,则该问题无解;否则,这里有一些c#给你:

int MinutesBetweenTwoTimes(int time1, int time2)
{
    return time1 < time2 ? time2 - time1 : (1440-time1) + time2;
}
bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime,
                         int secondStartTime, int secondEndTime)
{
    int totalSpannedTime = MinutesBetweenTwoTimes(firstStartTime, firstEndTime)
                           + MinutesBetweenTwoTimes(firstEndTime, secondStartTime) 
                           + MinutesBetweenTwoTimes(secondStartTime, secondEndTime);
    return totalSpannedTime > 1440;
}

我可能误解了,但你就不能检查一下是否firstStartTime <= secondEndTime?

如果我没看错的话,我认为这是可行的,不是吗?

bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime,
                     int secondStartTime, int secondEndTime)
{
   // Logically, you'll only have a span > 24 hours if one of them spans midnight
   if ( firstStartTime > firstEndTime || secondStartTime > secondEndTime )
   {
       // Check for period overlap:
       // If the second period doesn't span midnight, this means the first does.
       // So check for overlap:
       if ( secondStartTime <= secondEndTime && firstEndTime > secondStartTime ) 
         throw new Exception ("Periods cannot overlap");
       // If *both* periods span midnight, this means they logically overlap.
       else if ( firstStartTime > firstEndTime && secondStartTime > secondEndTime )
         throw new Exception ("Periods cannot overlap");
      // If we get to here, we know that the periods don't overlap, yet they span midnight
      // The answer now is simply if the end of the second span is after the first begins
      return secondEndTime > firstStartTime;
   }
   // Neither period span midnight, so overlap check is a snap:
   if ( firstEndTime > secondStartTime ) 
     throw new Exception ("Periods cannot overlap");
   // No errors (no overlaps) and no midnight span means
   // the only logical result is that this is not > 24 hours
   return false;
}

最新更新