我有一个UIDatePicker
只需要30分钟的时间间隔。在viewDidLoad
我希望将当前时间缩短到最近的半小时。我该怎么做呢?
答案 0 :(得分: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;
希望这有帮助!