Home > Mobile >  How can I compare the current time with a specific time?
How can I compare the current time with a specific time?

Time:05-19

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. I need to know if the label time is less than or greater than 4:00pm.

My 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

CodePudding user response:

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.

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:

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")
}
  • Related