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

故事扮演 提交于 2019-12-01 19:35:34

You can do this with your NSCalendar.

First, get your date:

NSDate *date = [timePicker date];

Next, convert it into its date components:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSIntegerMax fromDate:date];

Now we'll reset the hours and minutes of the date components so that it's now pointing at midnight:

[components setHour:0];
[components setMinute:0];
[components setSecond:0];

Next, we'll turn it back in to a date:

NSDate *midnight = [[NSCalendar currentCalendar] dateFromComponents:components];

Finally, we'll ask for the hours between midnight and the date:

NSDateComponents *diff = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:midnight toDate:date options:0];

NSInteger numberOfHoursPastMidnight = [diff hour];

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!