您的位置:首页 > 其它

判断当前时间是否在一个时间段范围内

2014-12-19 12:24 441 查看
+ (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour
{
NSDate *dateFromHour = [self getCustomDateWithHour:fromHour];
NSDate *dateToHour = [self getCustomDateWithHour:toHour];

NSDate *currentDate = [NSDate date];

if ([currentDate compare:dateFromHour]==NSOrderedDescending && [currentDate compare:dateToHour]==NSOrderedAscending)
{
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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐