[英]How can I compare the current time with a specific time?
I have a Label that contains the time in real time.我有一个包含实时时间的标签。 My question is how can I compare the time of the label with 4:00pm.
我的问题是如何将标签的时间与下午 4:00 进行比较。 I need to know if the label time is less than or greater than 4:00pm.
我需要知道标签时间是小于还是大于下午 4:00。
My viewDidLoad:我的viewDidLoad:
override func viewDidLoad() {
labelTiempo.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
labelFuncion.text = "Funcion: " + filme!.funcion!
}
//complement function
@objc func tick() {
labelTiempo.text = DateFormatter.localizedString(from: Date(), dateStyle: .none,timeStyle: .short)
}
[screenshot of the view containing the label.][1] [1]: https://i.stack.imgur.com/bIVxG.png [包含标签的视图的屏幕截图。][1] [1]:https://i.stack.imgur.com/bIVxG.png
Don't use a label to hold information.不要使用标签来保存信息。
Save the date at the moment you set your label's text, as a Date
, into your model (or simply as a property in your view controller.) Then, when you need to tell If the "label time" is before or after 4:00PM, use the Calendar method date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)
to generate a Date for 4:00 PM local time, and simply compare them.将标签文本设置为
Date
时的日期保存到模型中(或简单地作为视图控制器中的属性)。然后,当您需要判断“标签时间”是否在 4 之前或之后时: 00PM,使用 Calendar 方法date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)
生成当地时间下午 4:00 的 Date,并简单地比较它们。
class MyViewController: UIViewController {
var startTime: Date!
// Your other instance variables go here
override func viewDidLoad() {
startTime = Date()
labelTiempo.text = DateFormatter.localizedString(from: startTime, dateStyle: .none, timeStyle: .short)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
labelFuncion.text = "Funcion: " + filme!.funcion!
}
// Your view controller's other functions go here
}
Code to tell if the "label time" is before or after 4:00:判断“标签时间”是在 4:00 之前还是之后的代码:
let fourOClockToday = Calendar.current.date(bySettingHour: 16, minute: 0,second: 0 of: startTime)
if startTime < fourOClockToday {
print("The 'labelTime' is after 4:00 PM")
} else {
print("The 'labelTime' is ≤ 4:00 PM")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.