ios正在使用NSDateComponents、NSDate、NSCalendar它的结论是在当前时间是在一段时间在一天。

一般应用程序设置这一组的存在,比如夜间模式,如果你。从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]; } PS:有一种更好的方式牛逼,随后不久,你说,加群:172158202



posted @ 2015-12-09 11:41  mengfanrong  阅读(1149)  评论(0编辑  收藏  举报