Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if current time is between a range

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 between a time range?

I want to display a personalized greeting like the following:

12 pm - 4:59:9999 pm @"Good afternoon, foo"
5 pm - 11:59:9999 pm @"Good evening, foo"
12 am - 11:59:9999 am @"Good morning, foo"

like image 305
Tom Fobear Avatar asked Aug 04 '11 17:08

Tom Fobear


1 Answers

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")
}
like image 128
Joe Avatar answered Oct 20 '22 23:10

Joe