如何从 UIDatePicker 获取小时和分钟

How to get hours and minutes from UIDatePicker

如何从 UIDatePicker 中获取 hours: Intminutes: Int

我知道它有 .date 属性,但我发现很难直接透露小时和分钟值。有没有比我想到的 'hacky-ish' 方法更简单的方法,即将当前日期与 datePicker 的日期进行比较,然后将该时间间隔转换为小时和分钟并将其添加到当前小时和分钟。对于看似普通的任务来说似乎过于复杂...

UIDatePicker 只给你选择的 Date,如果你需要基于当前日历的日期组件,请查看 CalendarDateComponent 文档了解详细信息。

let now = Date() // your date
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: now)

dateComponents.hour
dateComponents.minute

如果您需要 hoursminutes 的时间距离,您需要使用您喜欢的基准日期手动计算它。