IOS,利用NSDateComponents,NSCalendar判断当前的时间点是否在某个时间段内的方法

 1 - (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour
 2 {
 3     NSDate *date8 = [self getCustomDateWithHour:8];
 4     NSDate *date23 = [self getCustomDateWithHour:23];
 5     NSDate *currentDate = [NSDate date];
 6     
 7     if ([currentDate compare:date8]==NSOrderedDescending && [currentDate compare:date23]==NSOrderedAscending)
 8     {
 9         NSLog(@"该时间在 %ld:00-%ld:00 之间!", (long)fromHour, (long)toHour);
10         return YES;
11     }
12     return NO;
13 }
14 /**
15  * @brief 生成当天的某个点(返回的是伦敦时间,可直接与当前时间[NSDate date]比较)
16  * @param hour 如hour为“8”,就是上午8:00(本地时间)
17  */
18 - (NSDate *)getCustomDateWithHour:(NSInteger)hour
19 {
20     //获取当前时间
21     NSDate *currentDate = [NSDate date];
22     
23     NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
24     NSDateComponents *currentComps = [[NSDateComponents alloc] init];
25     NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
26     // 生成当天的component
27     currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
28     //设置当天的某个点
29     NSDateComponents *resultComps = [[NSDateComponents alloc] init];
30     [resultComps setYear:[currentComps year]];
31     [resultComps setMonth:[currentComps month]];
32     [resultComps setDay:[currentComps day]];
33     [resultComps setHour:hour];
34     
35     // 根据resultCalendar和resultComps生成日期
36     NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
37     return [resultCalendar dateFromComponents:resultComps];
38 }

 

posted @ 2015-12-20 12:20  击水湘江  阅读(659)  评论(0编辑  收藏  举报