Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 957
Relex Avatar asked Feb 22 '13 08:02

Relex


1 Answers

So many answers and so many flaws...

You can use NSDateFormatter in order to get an user-friendly string from a date. But it is a very bad idea to use that string for date comparisons!
Please ignore any answer to your question that involves using strings...

If you want to get information about a date's year, month, day, hour, minute, etc., you should use NSCalendar and NSDateComponents.

In order to check whether a date is between 9:00 and 18:00 you can do the following:

NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];

if (dateComponents.hour >= 9 && dateComponents.hour < 18) {
    NSLog(@"Date is between 9:00 and 18:00.");
}

EDIT:
Whoops, using dateComponents.hour <= 18 will result in wrong results for dates like 18:01. dateComponents.hour < 18 is the way to go. ;)

like image 102
Fabian Kreiser Avatar answered Sep 28 '22 03:09

Fabian Kreiser