好吧,只有两次没有日期,您只能找出当前时间是否在开始时间和结束时间之间。这是因为,在上面的示例中(开始时间 22:30 和结束时间 04:00)你会在 13:00 返回什么?今天是“结束时间之后”(04:00)和“开始时间之前”(22:30)。
话虽如此,这是检查当前时间是否在两个日期中指定的时间之间的一种方法。您可以通过将所有内容保留为 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;
}
}