码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-12-20 13:12:07      阅读:608      评论:0      收藏:0      [点我收藏+]

标签:

 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 }

 

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

标签:

原文地址:http://www.cnblogs.com/Mike-Fighting/p/5060611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!