将TimeInterval转换为String <del> String To Time Interval </del>

时间:2016-11-30 16:26:13

标签: ios swift watchkit apple-watch health-kit

我有TimeInterval我必须将其转换为String,以便可以将其添加到通过Dictionary从Apple Watch传递到iPhone的WatchConnectivity

既然我拥有iPhone上的String,我需要将其重新设置为TimeInterval ,但我似乎无法弄明白

(我需要在显示锻炼期的持续时间的UILabel中显示。)

有什么想法吗?

例如

观看

<00> 00:15:15(小时,分钟,秒)变成&#34; 915.012948989868&#34;

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

iPhone

需要转向&#34; 915.012948989868&#34;回到00:15:15

3 个答案:

答案 0 :(得分:3)

使用calendar.dateComponents,您可以将915转换为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"
        }
    }

答案 1 :(得分:2)

而不是将时间间隔转换为字符串,而是将其转换为可添加到字典中的NSNumber。 NSTimeInterval只是一个双精度数,因此您可以轻松地将它转换为双精度数。

let timeInterval: TimeInterval = 915.012948989868

let dict = ["TimeIneterval": NSNumber(value: timeInterval)]

if let extractedTimeInterval: TimeInterval = dict["TimeIneterval"] as? TimeInterval {

    print(extractedTimeInterval)
}

答案 2 :(得分:1)

这可以作为TimeInterval的扩展来完成。此版本也正确处理分钟/秒&lt; 10通过填充它们。

extension TimeInterval {
    var formatted: String {
        let endingDate = Date()
        let startingDate = endingDate.addingTimeInterval(-self)
        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 "\(String(format: "%02d", hour)):\(String(format: "%02d", minute)):\(String(format: "%02d", seconds))"
        } else {
            return "00:00:00"
        }
    }
}

并处理字符串 - &gt; TimeInterval转换内联。

TimeInterval(intervalAsString).formatted