標籤:nsdate 時間間隔 時間段 判斷時間是否在某個時間段內
應用中設定一般會存在這樣的設定,如夜間勿擾模式,從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];}