Trying to calculate time difference, but am receiving negative answer

I am trying to calculate the time difference (x hrs x mins) between two timings, the current time, and the time set by user with the timepicker.

I would receive a negative value, e.g. -7 hrs 30 mins.

To solve this, I've read that i will need to include if statement. However, i receive the following error and am unable to solve it: "Cannot convert value of type 'Date' to expected argument type 'TimeInterval' (aka 'Double')"

would greatly appreciate some help, thanks!

func findTimeDiff() {
    let time1 = currentTimeOutlet
    let time2 = alarmTimeOutlet

    let formatter = DateFormatter()
    formatter.dateFormat = "hh:mma"

    let date1 = formatter.date(from: time1!.text!)
    let date2 = formatter.date(from: time2!.text!)

    var elapsedTime = date2!.timeIntervalSince(date1!)
    let hours = floor(elapsedTime / 60 / 60)
    let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)

    if (date2!) < (date1!) {

        var elapsedTime = ((date2! + 86400000) - date1!)
        let hours = floor(elapsedTime / 60 / 60)
        let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)
        timeDiffOutlet.text = ("\(Int(hours)) hr and \(Int(minutes)) min")
    }
    else {
        var elapsedTime = date2!.timeIntervalSince(date1!)
        let hours = floor(elapsedTime / 60 / 60)
        let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)
        timeDiffOutlet.text = ("\(Int(hours)) hr and \(Int(minutes)) min")

    }
}

Upvotes: 0

Views: 386

Answers (2)

Upholder Of Truth
Upholder Of Truth

Reputation: 4711

You should avoid performing calculations with hard coded values like this where dates and times are concerns. Instead it's much better to use the methods provided for you by the Calendar class.

So something like this:

func findTimeDiff2() {
    let time1 = currentTimeOutlet
    let time2 = alarmTimeOutlet

    let formatter = DateFormatter()
    formatter.dateFormat = "hh:mma"

    let date1 = formatter.date(from: time1!.text!)
    let date2 = formatter.date(from: time2!.text!)

    let components = Calendar.current.dateComponents([.hour, .minute], from: date1!, to: date2!)

    timeDiffOutlet.text = "\(abs(components.hour!)) hr and \(abs(components.minute!)) min"
}

Doing this means that situations such as daylight saving time will be handled for you although in this case as you don't know the day on which the alarm is taking place you won't be able to know if daylight saving applies or not. It would really be better to use a full date instead of just the time.

Upvotes: 1

OOPer
OOPer

Reputation: 47886

Why are you trying completely different expression in case of (date2!) < (date1!) ?

Try changing this line:

var elapsedTime = ((date2! + 86400000) - date1!)

To:

var elapsedTime = date1!.timeIntervalSince(date2!)

Upvotes: 0

Related Questions