Search code examples
iosswiftnsdatenstimeinterval

Convert NSTimeInterval to hours in decimals


I'm working on an app, in which I take the difference between 2 NSdates, and get the interval in between using NSTimeInterval

let timediff = timeDownValue?.timeIntervalSinceDate(timeUpValue!)

then using my new timeDiff constant, I update my timeTotals var

var totalTime = NSTimeInterval()

Now, what I need to do from there is to convert this NSTimeInterval to a Decimal, because that's what they use to calculate the time. so for example if my interval between date1 and date2 is 30 minutes, I want my final output to be 0.5

I can't seems to figure out how

thanks


Solution

  • Your timediff variable is already a decimal value for the number of seconds. To convert that into hours, divide by 3600.

    let timediff = timeDownValue?.timeIntervalSinceDate(timeUpValue!)
    var totalTime = timediff / 3600.0
    

    Here, totalTime will be in hours.