美文网首页ios 学习
iOS 获取某个时间段(2016.12)

iOS 获取某个时间段(2016.12)

作者: Amok校长 | 来源:发表于2016-12-08 15:52 被阅读0次

    #pragma mark---------------获取某个时间段----------------

    - (NSDate*)getCustomDateWithHour:(NSInteger)hour

    {

         //获取当前时间

         NSDate*currentDate = [NSDate date];

         NSCalendar*currentCalendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

         NSDateComponents*currentComps = [[NSDateComponents alloc]init];

         NSInteger unitFlags=NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;

         currentComps = [currentCalendar components:unitFlags fromDate:currentDate];

         NSLog(@"-----------weekday is %zd",[currentCompsweekday]);//在这里需要注意的是:星期日是数字1,星期一时数字2,以此类推。。。

       //设置当天的某个点

         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:NSCalendarIdentifierGregorian];

         return [resultCalendar dateFromComponents: resultComps];

    }

    - (BOOL)isBetweenFromHour:(NSInteger)fromHour  toHour:(NSInteger)toHour

    {

          NSDate*fromDate = [self getCustomDateWithHour:fromHour];

          NSDate*toDate = [self getCustomDateWithHour:toHour];

          NSDate*currentDate = [NSDate date];

          if([currentDate compare:fromDate] ==NSOrderedDescending&& [currentDate compare:toDate] ==NSOrderedAscending){

          NSLog(@"该时间在%ld:00-%ld:00之间!", (long)fromHour, (long)toHour);

          returnYES;

        } 

        returnNO;

    }

    相关文章

      网友评论

        本文标题:iOS 获取某个时间段(2016.12)

        本文链接:https://www.haomeiwen.com/subject/ikjsmttx.html