【问题标题】:UIDatePicker setting incorrect time when configured to use a 30 minute interval配置为使用 30 分钟间隔时,UIDatePicker 设置不正确的时间
【发布时间】:2012-10-05 05:21:16
【问题描述】:

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

【问题讨论】:

  • "在 viewDidLoad 上,我想将当前时间精确到最近的半小时。我该怎么做呢?"

标签: objective-c ios nsdate uidatepicker


【解决方案1】:

使用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;

希望这会有所帮助!

【讨论】:

  • 谢谢。它帮助我解决了其他问题。 :)
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
相关资源
最近更新 更多