ios - 将 TimeInterval 转换为字符串 <del>String To Time Interval</del>

标签 ios swift watchkit apple-watch healthkit

我有一个 TimeInterval 我必须将它变成一个 String 以便它可以添加到从 Apple Watch 传递的 Dictionary通过 WatchConnectivity 连接到 iPhone。

现在我在 iPhone 上有了 String,我需要把它变回 TimeInterval,但我似乎不能弄清楚这一点。

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

有什么想法吗?

例如

观看:

00:15:15(时、分、秒)变成“915.012948989868”

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

iPhone:

需要将“915.012948989868”转回00:15:15

最佳答案

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

关于ios - 将 TimeInterval 转换为字符串 <del>String To Time Interval</del>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40893338/

相关文章:

iphone - 将地址强制转换为 (id) 有副作用吗???地址 0xbfffe8d0 是否特殊? (固定 : issue was with _NSCallStackArray)

swift - 从 URL 检索并显示多个图像

ios - 在 WatchKit 中使用应用内购买功能来获得一目了然的功能和复杂功能

xcode - 使用 WatchKit (Watch) 的基于页面的界面中的页码?

ios - 如何判断通知是否可以发送到Apple Watch?

ios - 如何使用新 API willAnimateRotationToInterfaceOrientation 修复 iOS 方向

objective-c - NSPredicate,CoreData 中的空格。如何修剪谓词?

ios - 使您的自定义 View Controller 成为根 IOS

ios - @NSManaged 有什么作用?

ios - 将阴影渐变添加到 uitableviewcell/uiimageview 的底部