4

我有一个UIDatePicker只需要 30 分钟间隔的时间。OnviewDidLoad我想将当前时间精确到最接近的半小时。我该怎么做呢?

4

1 回答 1

4

用于NSDateComponents获取和操作日期的小时和分钟。我是这样做的:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) //Need to pass all this so we can get the day right later
                                           fromDate:[NSDate date]];
[components setCalendar:calendar]; //even though you got the components from a calendar, you have to manually set the calendar anyways, I don't know why but it doesn't work otherwise
NSInteger hour = components.hour;
NSInteger minute = components.minute;

//my rounding logic is maybe off a minute or so
if (minute > 45)
{
    minute = 0;
    hour += 1;
}
else if (minute > 15)
{
    minute = 30;
}
else
{
    minute = 0;
}

//Now we set the componentns to our rounded values
components.hour = hour;
components.minute = minute;

// Now we get the date back from our modified date components.
NSDate *toNearestHalfHour = [components date];
self.datePicker.date = toNearestHalfHour;

希望这可以帮助!

于 2012-10-05T07:32:32.267 回答