[iOS]判斷當前時間是否在指定的時間段內
阿新 • • 發佈:2019-02-18
一、問題描述
應用需要,判斷當前時間是否在指定的時間段內,從而進行不同的操作
二、問題解決
用NSDateComponents、NSCalendar確定倆固定的NSDate格式的時間,然後再進行比較
/** * @brief 判斷當前時間是否在fromHour和toHour之間。如,fromHour=8,toHour=23時,即為判斷當前時間是否在8:00-23:00之間 */ + (BOOL)isBetweenFromHour:(NSInteger)fromHour FromMinute:(NSInteger)fromMin toHour:(NSInteger)toHour toMinute:(NSInteger)toMin { NSDate *date8 = [self getCustomDateWithHour:8 andMinute:fromMin]; NSDate *date23 = [self getCustomDateWithHour:23 andMinute:toMin]; NSDate *currentDate = [NSDate date]; if ([currentDate compare:date8]==NSOrderedDescending && [currentDate compare:date23]==NSOrderedAscending) { NSLog(@"該時間在 %d:%d-%d:%d 之間!", fromHour, fromMin, toHour, toMin); return YES; } return NO; } /** * @brief 生成當天的某個點(返回的是倫敦時間,可直接與當前時間[NSDate date]比較) * @param hour 如hour為“8”,就是上午8:00(本地時間) */ + (NSDate *)getCustomDateWithHour:(NSInteger)hour andMinute:(NSInteger)minute { //獲取當前時間 NSDate *currentDate = [NSDate date]; NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *currentComps = [[NSDateComponents alloc] init]; NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; currentComps = [currentCalendar components:unitFlags fromDate:currentDate]; //設定當天的某個點 NSDateComponents *resultComps = [[NSDateComponents alloc] init]; [resultComps setYear:[currentComps year]]; [resultComps setMonth:[currentComps month]]; [resultComps setDay:[currentComps day]]; [resultComps setHour:hour]; [resultComps setMinute:minute]; NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; return [resultCalendar dateFromComponents:resultComps]; }