How to check whether now date is during 9:00-18:00

前端 未结 2 1790
感动是毒
感动是毒 2021-02-05 18:32

When my app is launched I want to check whether the date is between 9:00-18:00.

And I can get the time of now using NSDate. How can I check the time?

2条回答
  •  不要未来只要你来
    2021-02-05 19:12

    Construct dates for 09:00 and 18:00 today and compare the current time with those dates:

    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *components = [cal components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
    
    [components setHour:9];
    [components setMinute:0];
    [components setSecond:0];
    NSDate *nineHundred = [cal dateFromComponents:components];
    
    [components setHour:18];
    NSDate *eighteenHundred = [cal dateFromComponents:components];
    
    if ([nineHundred compare:now] != NSOrderedDescending &&
        [eighteenHundred compare:now] != NSOrderedAscending)
    {
        NSLog(@"Date is between 09:00 and 18:00");
    }
    

提交回复
热议问题