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

前端 未结 2 808
一生所求
一生所求 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:05

    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];
    

提交回复
热议问题