/**
if ([self isBetweenFromHour:9 toHour:15]) {
LOG(@"处于时间段内");
}else {
LOG(@"处于时间段外");
}
* @brief 判断当前时间是否在fromHour和toHour之间。如,fromHour=8,toHour=23时,即为判断当前时间是否在8:00-23:00之间
*/
- (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour {
NSDate *dateFrom = [self getCustomDateWithHour:fromHour];
NSDate *dateTo = [self getCustomDateWithHour:toHour];
NSDate *currentDate = [NSDate date];
LOG(@"dateFrom=%@---dateTo=%@---currentDate=%@",dateFrom,dateTo,currentDate);
if ([currentDate compare:dateFrom]==NSOrderedDescending && [currentDate compare:dateTo]==NSOrderedAscending) {
// 当前时间在9点和10点之间
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:NSCalendarIdentifierGregorian];
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:NSCalendarIdentifierGregorian];
return [resultCalendar dateFromComponents:resultComps];
}
iOS 判断当前时间是否处于某个时间段内
最新推荐文章于 2022-04-15 10:18:47 发布