ios 判断当前时间是否在某个时间段的方法

- (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)

    {

        NSLog(@"该时间在 %ld:00-%ld:00 之间!", (long)fromHour, (long)toHour);

        return YES;

    }

    return NO;

}

- (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];

}

posted @ 2016-02-15 15:58  ishizhen  阅读(1468)  评论(0编辑  收藏  举报