Swift 如何获取 DatePicker 时间到 Calendar 组件并插入到 Label 组件

How to get DatePicker time to Calendar component and insert to Label component in Swift

我是这个论坛的新手,但它对我编码有很大帮助。

目前我正尝试在 Swift (Xcode 11.2.1)

中编写一个 iOS 应用程序作为时间计算器

它应该可以从DatePicker 组件中选择一个时间并添加8 小时的工作时间。 所以功能是显示你可以离开你的工作场所的时间,而不会在你的弹性工作时间中得到负面影响。

应该显示在Label组件中


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var dateLabel: UILabel!

    @IBOutlet weak var datePicker: UIDatePicker!

    @IBAction func datePickerChanged(_ sender: Any) {

        let dateFormatter = DateFormatter()

        dateFormatter.timeStyle = DateFormatter.Style.short //show time in h:mm format

        dateFormatter.locale = Locale(identifier: "de-DE") //locale Germany

        let endTime = dateFormatter.date // declaring as date

        let calendar = Calendar.date(from: endTime) // get time from UIDatePicker

        let addHours = Calendar.date(byAdding: .hour, value: 8, to: endTime) // add 8 hours

        let endTimeString = dateFormatter.string(from: endTime) //convert time from date to String

        dateLabel.text = endTimeString // show calculated time in UILabel
    }
}

我遇到了 3 个错误。

在第一个 let calendar 行中写着:

Instance member 'date' cannot be used on type 'Calendar'; did you mean to use a value of this type instead?

在下面的 let addHours 行中,我再次遇到同样的错误,这里有什么意义?

当我尝试将时间类型从日期类型转换为字符串时,最后一个错误开始于该行。

Cannot convert value of type '(String) -> Date?' to expected argument type 'Date'

有人能帮帮我吗?

我想你想要这样的东西:

@IBAction func datePickerChanged(_ sender: UIDatePicker) {

    var pickerDate = sender.date

    let calendar = Calendar.current
    guard let endDate = calendar.date(byAdding: .hour, value: 8, to: pickerDate) else { return }

    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.short //show time in h:mm format
    dateFormatter.locale = Locale(identifier: "de-DE") //locale Germany
    var endTimeString = dateFormatter.string(from: endDate) //convert time from date to String
    dateLabel.text = endTimeString // show calculated time in UILabel

}

首先,您需要从 UIDatePicker 中获取选定的日期。 然后,对于日期计算,您需要指定要使用的 calendar。通常 current 日历就是您想要的(这是为设备指定的日历)。然后,加上 8 小时并将其转换为字符串。

顺便说一句:您需要记住,当用户选择晚上的日期时,当您添加 8 小时时会有 "day flip"。

更新

要添加 8 小时 13 分钟之类的内容,最好使用 DateComponents:

var now = Date()
var calendar = Calendar.current
var addComp = DateComponents(calendar:calendar,
                             hour:8,
                             minute:13)

if let then = calendar.date(byAdding: addComp, to: now, wrappingComponents:false) {
    print(now)
    print(then!)
}