Find if current time is between a range

前端 未结 5 1658
孤城傲影
孤城傲影 2021-02-08 11:22

I can find how to get if a date is between a range, but I cant seem how to create a date at a specific time.

What would be the simplest way to see if [NSDate date] is be

5条回答
  •  伪装坚强ぢ
    2021-02-08 11:53

    Yes you can using NSDateComponents which will return the hour in the 24 hour format.

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:[NSDate date]];
    NSInteger hour = [components hour];
    
    if(hour >= 0 && hour < 12)
        NSLog(@"Good morning, foo");
    else if(hour >= 12 && hour < 17)
        NSLog(@"Good afternoon, foo");
    else if(hour >= 17)
        NSLog(@"Good evening, foo");
    

    Swift 3

    let hour = Calendar.current.component(.hour, from: Date())
    
    if hour >= 0 && hour < 12 {
        print("Good Morning")
    } else if hour >= 12 && hour < 17 {
        print("Good Afternoon")
    } else if hour >= 17 {
        print("Good Evening")
    }
    

提交回复
热议问题