如何从 Swift 中的时间间隔减去 30 分钟?
How to subtract 30 minutes from a timeinterval in Swift?
我制作了一个带有日期选择器和 2 个按钮的应用程序 - "Check in" 和 "Check out"。我以小时和分钟为单位计算了两个时间戳之间的时间。
现在我想从那个时间间隔中减去 30 分钟,如果 "Check in" 在 12:00 之前。
到目前为止,这是我的代码:
var start = Date()
var end = Date()
class ViewController: UIViewController {
@IBOutlet weak var timeWheel: UIDatePicker!
@IBOutlet weak var workLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func checkIn(_ sender: Any) {
start = timeWheel.date
workLabel.text = ""
}
@IBAction func checkOut(_ sender: Any) {
end = timeWheel.date
let difference = Calendar.current.dateComponents([.hour, .minute], from: start, to: end)
workLabel.text = "\(difference.hour ?? 0) timer og \(difference.minute ?? 0) minutter"
}
}
有什么建议吗?
在计算差异之前获取 start
的 hour
分量并检查它是否小于 12。如果是,减去 30 分钟,然后进行数学运算
@IBAction func checkOut(_ sender: Any) {
end = timeWheel.date
let calendar = Calendar.current
let startHour = calendar.component(.hour, from: start)
let startDate = startHour < 12 ? calendar.date(byAdding: .minute, value: 30, to: start)! : start
let difference = calendar.dateComponents([.hour, .minute], from: startDate, to: end)
workLabel.text = "\(difference.hour!) timer og \(difference.minute!) minutter"
}
强制展开组件非常好,因为明确要求两个组件。
我制作了一个带有日期选择器和 2 个按钮的应用程序 - "Check in" 和 "Check out"。我以小时和分钟为单位计算了两个时间戳之间的时间。 现在我想从那个时间间隔中减去 30 分钟,如果 "Check in" 在 12:00 之前。
到目前为止,这是我的代码:
var start = Date()
var end = Date()
class ViewController: UIViewController {
@IBOutlet weak var timeWheel: UIDatePicker!
@IBOutlet weak var workLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func checkIn(_ sender: Any) {
start = timeWheel.date
workLabel.text = ""
}
@IBAction func checkOut(_ sender: Any) {
end = timeWheel.date
let difference = Calendar.current.dateComponents([.hour, .minute], from: start, to: end)
workLabel.text = "\(difference.hour ?? 0) timer og \(difference.minute ?? 0) minutter"
}
}
有什么建议吗?
在计算差异之前获取 start
的 hour
分量并检查它是否小于 12。如果是,减去 30 分钟,然后进行数学运算
@IBAction func checkOut(_ sender: Any) {
end = timeWheel.date
let calendar = Calendar.current
let startHour = calendar.component(.hour, from: start)
let startDate = startHour < 12 ? calendar.date(byAdding: .minute, value: 30, to: start)! : start
let difference = calendar.dateComponents([.hour, .minute], from: startDate, to: end)
workLabel.text = "\(difference.hour!) timer og \(difference.minute!) minutter"
}
强制展开组件非常好,因为明确要求两个组件。