SRMR SRMR - 9 days ago 5
Swift Question

Convert String to Time Interval

I have a

TimeInterval
I had to turn it into a
String
so it could be added to the
Dictionary
that gets passed from Apple Watch to iPhone via
WatchConnectivity
.

Now that I have the
String
on the iPhone, I need to turn it back into a
TimeInterval
, but I can't seem to figure that out.

(I need to display this in a
UILabel
that shows the duration of the workout session.)

Any ideas?

For Example

Watch:

00:15:15 (hours, minutes, seconds) turns into "915.012948989868"

let myDouble = computeDurationOfWorkout(withEvents: hkWorkout?.workoutEvents, startDate: hkWorkout?.startDate, endDate: hkWorkout?.endDate)
let myDoubleString = String(myDouble)
durationVariableString = myDoubleString


iPhone:

Need to turn "915.012948989868" back into 00:15:15

Answer

Using calendar.dateComponents you can convert 915 to 00:15:15

func stringFromTimeInterval (interval: String) -> String {
        let endingDate = Date()
        if let timeInterval = TimeInterval(interval) {
            let startingDate = endingDate.addingTimeInterval(-timeInterval)
            let calendar = Calendar.current

            var componentsNow = calendar.dateComponents([.hour, .minute, .second], from: startingDate, to: endingDate)
            if let hour = componentsNow.hour, let minute = componentsNow.minute, let seconds = componentsNow.second {
                return "\(hour):\(minute):\(seconds)"
            } else {
                return "00:00:00"
            }

        } else {
            return "00:00:00"
        }
    }