//使用示例
if ([self isBetweenFromHour:9 toHour:10]) {
}
/**
* 判斷當(dāng)前時(shí)間是否在fromHour和toHour之間。如敌呈,fromHour=8,toHour=23時(shí),即為判斷當(dāng)前時(shí)間是否在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];
if ([currentDate compare:dateFrom]==NSOrderedDescending && [currentDate compare:dateTo]==NSOrderedAscending) {
// 當(dāng)前時(shí)間在9點(diǎn)和10點(diǎn)之間
return YES;
}
return NO;
}
/**
* @brief 生成當(dāng)天的某個(gè)點(diǎn)(返回的是倫敦時(shí)間倍宾,可直接與當(dāng)前時(shí)間[NSDate date]比較)
* @param hour 如hour為“8”则果,就是上午8:00(本地時(shí)間)
*/
- (NSDate *)getCustomDateWithHour:(NSInteger)hour {
//獲取當(dāng)前時(shí)間
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];
//設(shè)置當(dāng)天的某個(gè)點(diǎn)
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];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者