如何将当前时间与特定时间进行比较?

How can I compare the current time with a specific time?

我有一个包含实时时间的标签。 我的问题是如何将标签的时间与 4:00pm 进行比较。 我需要知道标签时间是小于还是大于4:00pm.

我的 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)
    }

[包含标签的视图的屏幕截图。][1] [1]: https://i.stack.imgur.com/bIVxG.png

不要使用标签来保存信息。

将设置标签文本时的日期作为 Date 保存到模型中(或仅作为视图控制器中的 属性。)然后,当您需要时告诉如果“标签时间”在4:00PM之前或之后,使用日历方法date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)生成当地时间4:00下午的日期,并简单地比较它们。

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

}

判断“标签时间”是在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")
}