Search code examples
iphoneobjective-cnsdatenstimeinterval

How to store and compare time data objects


This should be really simple!

I have a shop, it opens at 8:30 and closes at 17:00. I want my app to say the shops current open or currently closed.

Whats the best way to store my open_time and close_time? Store them as seconds since the start of the day, i.e. 30600 and 63000?

This make sense, but how do I get the current time right now, in seconds since the begining of today, so I can check if current_time is between open_time and close_time, i.e. open!!

Thanks in advance!


Solution

  • This problem isn't quite as trivial as you may think. You have to work with dates very carefully. The best solution is to store all of your open and close times as dates. Here is some code for creating your open/close times and comparing them:

    NSDate * now = [NSDate date];
    NSCalendar * calendar = [NSCalendar currentCalendar];
    NSDateComponents * comps = [calendar components:~(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
    [comps setHour:8];
    [comps setMinute:30];
    NSDate * open = [calendar dateFromComponents:comps];
    [comps setHour:17];
    [comps setMinute:0];
    NSDate * close = [calendar dateFromComponents:comps];
    
    if ([now compare:open] == NSOrderedDescending && [now compare:close] == NSOrderedAscending) {
        // The date is within the shop's hours.
    }
    else {
        // The date is not within the shop's hours.
    }
    

    Here's what I did:

    1. Grab the current date.

    2. Get the components of the date, except hours, minutes, and seconds.

    3. Set the hour and minutes.

    4. Create an open time.

    5. Repeat steps 3-4 for close time.

    6. Compare open and close times to now.

    If you ever need to do any modification of dates, you should always use NSCalendar and NSDateComponents. Check out this answer for why it's so important.