应用中设置一般会存在这样的设置,如夜间勿扰模式,从8:00-23:00,此时如何判断当前时间是否在该时间段内。难点主要在于如何用NSDate生成一个8:00的时间和23:00的时间,然后用当前的时间跟这俩时间作对比就好了。
下面提供两条思路:
法1.用NSDate生成当前时间,然后转为字符串,从字符串中取出当前的年、月、日,然后再拼上时、分、秒,然后再将拼接后的字符串转为NSDate,最后用当前的时间跟自己生成的俩NSDate的时间点比较。(该方法比较笨,也不难,但看起来有点太菜了,看上去不怎么规范)
法2.用NSDateComponents、NSCalendar确定俩固定的NSDate格式的时间,然后再进行比较(此方法比较装逼,其实跟拼字符串的方法复杂度差不了多少,但看起来比较规范,像是大神写的)。
/** * @brief 判断当前时间是否在fromHour和toHour之间。如,fromHour=8,toHour=23时,即为判断当前时间是否在8:00-23:00之间 */ - (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour { NSDate *date8 = [self getCustomDateWithHour:8]; NSDate *date23 = [self getCustomDateWithHour:23]; NSDate *currentDate = [NSDate date]; if ([currentDate compare:date8]==NSOrderedDescending && [currentDate compare:date23]==NSOrderedAscending) { NSLog(@"该时间在 %d:00-%d:00 之间!", fromHour, toHour); return YES; } return NO; } /** * @brief 生成当天的某个点(返回的是伦敦时间,可直接与当前时间[NSDate date]比较) * @param hour 如hour为“8”,就是上午8:00(本地时间) */ - (NSDate *)getCustomDateWithHour:(NSInteger)hour { //获取当前时间 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]; NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; return [resultCalendar dateFromComponents:resultComps]; }
2.
http://stackoverflow.com/questions/12238395/check-if-the-current-time-is-in-between-time-a-and-b
3.
http://stackoverflow.com/questions/4084341/how-to-calculate-time-in-hours-between-two-dates-in-ios
3.
http://stackoverflow.com/questions/13965921/ios-check-whether-current-time-is-between-two-times-or-not
原文:http://www.cnblogs.com/lihaibo-Leao/p/4276202.html