views:

116

answers:

2

I haven't used NSDate that much, so I'd like some help with a calculation I am doing.

I have an integer that has my store's closing hour in minutes since midnight. Basically, my store closes at 5.00PM, which gives me the integer 1020.

So right now it's 10.45PM or 22.45. Integer since 00:00 is 1365, and from this I can say

if (storeHour < currentTime) {
      // closed!
}

However, I don't know how I get from "22.45" that I have from NSDate to converting it to an integer representing time since 00:00. Is there something in NSDate that can help me with that?

Thx

A: 

If you have another NSDate which is set to midnight, then you can use the timeIntervalSinceDate method of the NSDate object to get an NSTimeInterval back with the difference between the two. Alternatively, if you're always wanting to compare midnight with the current time, you could call the timeIntervalSinceNow method on the midnight NSDate and you'd get an NSTimeInterval back (albeit negative) with the difference between midnight and the current time.

NSTimeInterval is defined as a double by the standard which holds a number of seconds (and any fractional seconds).

Amber
+1  A: 

I do recommend using an NSDate object to store the time the store closes instead of using your own custom integer format. It's unfortunate that NSDate represents both date and time of date.

In any case, you can check NSDateComponents. You can have a utilities method like:

int minutesSinceMidnight:(NSDate *)date
{
    NSCalendar *gregorian = [[NSCalendar alloc]
        initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned unitFlags =  NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags fromDate:date];

    return 60 * [components hour] + [components minute];    
}
notnoop
Thanks, that did it for me :)
Canada Dev