如何使用NSDatePicker更新日期集并保持时间不变?

时间:2019-01-16 10:24:27

标签: swift macos nsdate nsformatter

我正在尝试使用NSDatePicker设置事件应该发生的时间。但是,不幸的是,此控件用于设置完整日期,因此当我必须使用该值时,它可能属于过去。我的目标是使用datePicker设置将来的时间。

enter image description here

要创建这次保存的将来日期,我尝试设置一个循环,以增加一天的时间直到到达将来的点,但这在时间和处理方面似乎非常昂贵,或者我尝试手动建立日期只用时间。不幸的是,由于缺乏对此问题的经验,我认为我没有找到可行的解决方案。

这是我正在使用的代码:

// getting date value from a NSDatePicker
let date = myDatePicker.dateValue

// learn if the date is in future or in past
if date.timeIntervalSince(currentDate as Date).sign == FloatingPointSign.minus {

    print("\(date) is in past") // update adding days to make it in future

    // get the hour and minute from the date
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HH:mm" // only hour and second
    let timeString = timeFormatter.string(from: date as Date)

    print("\(timeString)") // here I get "18:10" or "6:10 PM" based on system preferences (12 or 24)

    // create a date in future that use this hours

} else {

    // the date is already in future, just use it
    ...
}

我在Stack Overflow上发现了几个问题,这些问题有助于我更好地了解如何使用NSDateFormatter,以及一个出色的在线教程http://www.knowstack.com/swift-nsdateformatter/。我还发现了一些与我的问题类似的问题,例如:returns a date an hour in the futureinit] returning date an hour in the past?,但它们并没有帮助我。

Apple开发人员文档: NSDatePicker NSDateFormatter

0 个答案:

没有答案