【发布时间】:2012-10-05 05:21:16
【问题描述】:
我有一个UIDatePicker,它只需要 30 分钟间隔的时间。在viewDidLoad 我想将当前时间精确到最接近的半小时。我该怎么做呢?
【问题讨论】:
-
"在 viewDidLoad 上,我想将当前时间精确到最近的半小时。我该怎么做呢?"
标签: objective-c ios nsdate uidatepicker
我有一个UIDatePicker,它只需要 30 分钟间隔的时间。在viewDidLoad 我想将当前时间精确到最接近的半小时。我该怎么做呢?
【问题讨论】:
标签: objective-c ios nsdate uidatepicker
使用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;
希望这会有所帮助!
【讨论】: