zoukankan      html  css  js  c++  java
  • 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];
    }
  • 相关阅读:
    【C语言天天练(三)】typedef具体解释
    操作系统之基本分页存储管理方式
    线索二叉树创建及删除
    SVN:This client is too old to work with working copy…解决的方法
    android4.2 telephone应用层分析
    JPA学习笔记(3)——JPA注解
    Android研发中对String的思考(源代码分析)
    《Effective Modern C++》翻译--条款2: 理解auto自己主动类型推导
    “2014年CityEngine三维建模与设计精英培训班”——全国巡回举办
    Git命令总结
  • 原文地址:https://www.cnblogs.com/hero11223/p/5174817.html
Copyright © 2011-2022 走看看