iOS - 判断当前时间是否在某个时间段

2017-06-29  本文已影响287人  别人家的程序员
//使用示例
if ([self isBetweenFromHour:9 toHour:10]) {  
}  
/** 
 * 判断当前时间是否在fromHour和toHour之间。如,fromHour=8,toHour=23时,即为判断当前时间是否在8:00-23:00之间 
 */  
- (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour {  
      
    NSDate *dateFrom = [self getCustomDateWithHour:fromHour];  
    NSDate *dateTo = [self getCustomDateWithHour:toHour];  
      
    NSDate *currentDate = [NSDate date];  
    if ([currentDate compare:dateFrom]==NSOrderedDescending && [currentDate compare:dateTo]==NSOrderedAscending) {  
        // 当前时间在9点和10点之间  
        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];  
} 
上一篇下一篇

猜你喜欢

热点阅读