時刻が 2 つだけで日付がないため、現在の時刻が開始時刻と終了時刻の間にあるかどうかしかわかりません。これは、上記の例 (開始時間 22:30 と終了時間 04:00) では、13:00 に何を返すのでしょうか? 今日は「終了時刻後」(04:00)と「開始時刻前」(22:30)の両方です。
そうは言っても、現在の時刻が 2 つの日付で指定された時刻の間にあるかどうかを確認する 1 つの方法を次に示します。すべてを NSDate として (カレンダー操作を使用して) 保持することでこれを行うことができますが、指定された時間で今日の日付を使用して新しい NSDate オブジェクトを作成する必要があるため、さらに複雑になります。それほど難しくはありませんが、他の場所で使用していない限り、これを行う理由はありません。
// Take a date and return an integer based on the time.
// For instance, if passed a date that contains the time 22:30, return 2230
- (int)timeAsIntegerFromDate:(NSDate *)date {
NSCalendar *currentCal = [NSCalendar currentCalendar];
NSDateComponents *nowComps = [currentCal components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:date];
return nowComps.hour * 100 + nowComps.minute;
}
// Check to see if the current time is between the two arbitrary times, ignoring the date portion:
- (BOOL)currentTimeIsBetweenTimeFromDate1:(NSDate *)date1 andTimeFromDate2:(NSDate *)date2 {
int time1 = [self timeAsIntegerFromDate:date1];
int time2 = [self timeAsIntegerFromDate:date2];
int nowTime = [self timeAsIntegerFromDate:[NSDate date]];
// If the times are the same, we can never be between them
if (time1 == time2) {
return NO;
}
// Two cases:
// 1. Time 1 is smaller than time 2 which means that they are both on the same day
// 2. the reverse (time 1 is bigger than time 2) which means that time 2 is after midnight
if (time1 < time2) {
// Case 1
if (nowTime > time1) {
if (nowTime < time2) {
return YES;
}
}
return NO;
} else {
// Case 2
if (nowTime > time1 || nowTime < time2) {
return YES;
}
return NO;
}
}