在 iOS 中判斷目前時間是否落在某個時段,例如夜間勿擾模式,可以使用 NSCalendar 與 NSDateComponents 建立當天的指定時間點,再與目前時間比較。
- (NSDate *)getCustomDateWithHour:(NSInteger)hour {
NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSInteger year = [[calendar components:NSYearCalendarUnit fromDate:currentDate] year];
NSInteger month = [[calendar components:NSMonthCalendarUnit fromDate:currentDate] month];
NSInteger day = [[calendar components:NSDayCalendarUnit fromDate:currentDate] day];
NSDateComponents *resultComps = [[NSDateComponents alloc] init];
[resultComps setYear:year];
[resultComps setMonth:month];
[resultComps setDay:day];
[resultComps setHour:hour];
NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
return [resultCalendar dateFromComponents:resultComps];
}- (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour {
NSDate *fromDate = [self getCustomDateWithHour:fromHour];
NSDate *toDate = [self getCustomDateWithHour:toHour];
NSDate *currentDate = [NSDate date];
if ([currentDate compare:fromDate] == NSOrderedDescending && [currentDate compare:toDate] == NSOrderedAscending) {
return YES;
}
return NO;
}這種做法比字串拼接更清楚,也比較容易維護。