Settings in the app generally have such settings, such as the night do Not Disturb mode, from 8:00-23:00, at this point how to determine whether the current time is within that time period. The main difficulty is how to use NSDate to generate a 8:00 of the time and 23:00 of the time, and then use the current time to compare these two times.
Two ideas are provided below:
Method 1. Use NSDate to generate the current time, and then into a string, take the current year, month, day from the string, and then spell the time, minutes, seconds, and then the concatenation of the string into NSDate, and finally use the current time with their own generation of the two nsdate time point comparison. (This method is stupid, it is not difficult, but it seems to be a little too much food, it does not look very normative)
Method 2. Use Nsdatecomponents, Nscalendar to determine the time of the two fixed nsdate format, and then compare (this method compared loading force, in fact, with the method of spelling string complexity is not much difference, but looks more normative, like the Great God wrote).
?
| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
/** * @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];} |
Use Nsdatecomponents, NSDate, Nscalendar in iOS to determine whether the current time is within a certain time of day