應用中設置一般會存在這樣的設置,如夜間勿擾模式,從8:00-23:00,此時如何判斷當前時間是否在該時間段內。難點主要在於如何用NSDate生成一個8:00的時間和23:00的時間,然後用當前的時間跟這倆時間作對比就好了。
下面提供兩條思路:
法1.用NSDate生成當前時間,然後轉為字符串,從字符串中取出當前的年、月、日,然後再拼上時、分、秒,然後再將拼接後的字符串轉為NSDate,最後用當前的時間跟自己生成的倆NSDate的時間點比較。(該方法比較笨,也不難,但看起來有點太菜了,看上去不怎麼規范)
法2.用NSDateComponents、NSCalendar確定倆固定的NSDate格式的時間,然後再進行比較(此方法比較裝逼,其實跟拼字符串的方法復雜度差不了多少,但看起來比較規范,像是大神寫的)。
/**
* @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];
}