How to subtract 30 minutes from a timeinterval in Swift?

1.1k Views Asked by At

I have made an App with a datePicker and 2 buttons - "Check in" and "Check out". I did the calculation between the two timestamps in hours and minutes. Now I want to subtract 30 minutes from that time interval, IF the "Check in" is before 12:00.

This is my code so far:

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"
}
}

Got any suggestions ?

1

There are 1 best solutions below

6
vadian On BEST ANSWER

Before calculating the difference get the hour component of start and check if it's less than 12. If yes subtract the 30 minutes and then do the math

@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"
}

Forces unwrapping the components is perfectly fine as both components were clearly requested.