Search code examples
swiftif-statementtimernsdateformattertimespan

create if statement based on time


I want my swift code to follow a if statement based on a certain time. My timer is in military time right now. So I want to do something like if the hour in time is 01:00 to 01:59. Then the view background color should turn blue. So I am just trying to control the hour time in the time style.

import UIKit

class ViewController: UIViewController {
    var box = UILabel()

    @objc func tick() {
        box.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
    }
    
    var timer = Timer()

    var currentDateTime = Date()

    lazy var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm" // or "hh:mm a" if you need to have am or pm symbols
        return formatter
    }()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        
        dateFormatter.timeStyle = .medium

        box.text = "\(dateFormatter.string(from: currentDateTime))"      
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        box.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)
        box.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(box)
        box.backgroundColor = .red   
        NSLayoutConstraint.activate([
            box.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
            box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
            box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            box.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
    }

}

Solution

  • If I understand exactly what you want to do, this code should help you:

    ...
        var box = UILabel()
    
        @objc func tick() {
            box.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
            
            let minutesNow = getMinutesFromDate(date: Date())
            
            if  minutesNow >= 60 && minutesNow < 120  {
                box.backgroundColor = .blue
            }
            else {
                box.backgroundColor = .red
            }
        }
        
        func getMinutesFromDate(date: Date) -> Int {
            let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)
            let minutes = ((dateComponents.hour ?? 0) * 60) + (dateComponents.minute ?? 0)
            return minutes
        }
    ...