How to retrieve number of hours past midnight from an NSDate object?

前端 未结 2 812
一生所求
一生所求 2021-01-19 22:44

I need to retrieve the number of hours past midnight from a UIDatePicker control in an iPhone project. datePickerMode is set to UIDatePickerModeTime

2条回答
  •  死守一世寂寞
    2021-01-19 23:22

    Dave's answer is correct, however it is not as performant as the example below. In my Instruments profile tests my solution was more than 3x as fast -- the total time taken by his method across all calls in my test app was 844ms, mine 268ms.

    Keep in mind that my test app iterates over a collection of objects to calculate the minutes since midnight of each, which is then used as a basis for sorting. So, if your code isn't doing something similar, his more-readable, more-standard answer is probably a better choice.

    int const MINUTES_IN_HOUR  = 60;
    int const DAY_IN_MINUTES   = 1440;
    
    #define DATE_COMPONENTS (NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)
    #define CURRENT_CALENDAR [NSCalendar currentCalendar]
    
    - (NSUInteger)minutesSinceMidnight 
    {
        NSDateComponents *startComponents = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self.startTime];
        NSUInteger fromMidnight = [startComponents hour] * MINUTES_IN_HOUR + [startComponents minute];
    
        return fromMidnight;
    }
    

提交回复
热议问题