objective-c - UIDatePicker 在配置为使用 30 分钟间隔时设置不正确的时间

标签 objective-c ios nsdate uidatepicker

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

最佳答案

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

希望这对您有所帮助!

关于objective-c - UIDatePicker 在配置为使用 30 分钟间隔时设置不正确的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12739962/

相关文章:

iOS:如何在没有数据库的情况下临时持久化数据?

objective-c - IOS - ObjC - 来自 NSString 的 JSONString

ios - 如何知道 UITableView 中 "On"的 UISwitch 的数量?

ios - 2 出现在标注上的 AccessoryItems

ios - 无法使用日期选择器在 tableview 单元格内更新带有新日期的标签

mysql - 如何将 MySQL 日期时间转换为 NSDate?

objective-c - 如何测试异步方法?

swift - 如何在每天开始时重置变量?

ios - UILocalNotification-在每个时区的6:00 am触发

ios - 我应该在 iOS 应用程序中将图像保存到本地存储吗?