1. 程式人生 > >iOS判斷當前時間是否在某個時間段

iOS判斷當前時間是否在某個時間段

if ([self isBetweenFromHour:9 toHour:10]) {
}

/**
 * @brief 判斷當前時間是否在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];
}