您的位置:首页 > 移动开发 > IOS开发

ios中利用NSDateComponents、NSDate、NSCalendar判断当前时间是否在一天的某个时间段内。

2014-07-25 19:15 1131 查看
        应用中设置一般会存在这样的设置,如夜间勿扰模式,从8:00-23:00,此时如何判断当前时间是否在该时间段内。难点主要在于如何用NSDate生成一个8:00的时间和23:00的时间,然后用当前的时间跟这俩时间作对比就好了

#import "ViewController.h"

@interface
ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{

    [super
viewDidLoad];

    NSDate *date8 = [self
getCustomDateWithHour:8];

    NSDate *date23 = [self
getCustomDateWithHour:16];

    
   
NSDate *currentDate = [NSDate
date];

    
   
if ([currentDate compare:date8]==NSOrderedDescending && [currentDate
compare:date23]==NSOrderedAscending)
    {
       
NSLog(@"该时间在
之间!");

       
    }
   
else
    {
       
NSLog(@"不在");
    }

    
}

/**

 * @brief
判断当前时间是否在fromHour和toHour之间。如,fromHour=8,toHour=23时,即为判断当前时间是否在8:00-23:00之间

 */
- (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour
{

    NSDate *date8 = [self
getCustomDateWithHour:8];

    NSDate *date23 = [self
getCustomDateWithHour:23];

    
   
NSDate *currentDate = [NSDate
date];

    
   
if ([currentDate compare:date8]==NSOrderedDescending && [currentDate
compare:date23]==NSOrderedAscending)
    {
       
NSLog(@"该时间在 %d:00-%d:00
之间!", fromHour, toHour);
       
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];
}

- (void)didReceiveMemoryWarning
{

    [super
didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐