标签的时间持续时间

时间:2018-05-03 02:22:00

标签: ios swift date time dateformatter

我在这里查看了所有与获取持续时间有关的代码。我需要做的只是花一点时间在这个格式的标签hr:m:s例如20:23:04。我需要从currentTime.StringValue和oldTime.StringValue的时间中获取时间,然后让它在durationOfTime.StringValue中显示小时的持续时间。

所以比如说currentTime = 11:00:04和oldTime = 9:00:04然后我想durationOfTime = 2hr' s。

现在我有一个代码可以获得时间并以上面的格式存储它。但是我遇到了各种问题,在这里尝试不同的代码与时间持续时间有关。

2 个答案:

答案 0 :(得分:2)

使用2个格式化程序:DateFormatter将字符串转换为Date个对象,使用DateComponentFormatter显示2 Date s之间的持续时间:

let currentTimeStr = "11:00:04"
let oldTimeStr = "9:00:04"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"

let dateComponentFormatter = DateComponentsFormatter()
dateComponentFormatter.allowedUnits = [.hour, .minute]
dateComponentFormatter.unitsStyle = .short

if let currentTime = dateFormatter.date(from: currentTimeStr),
    let oldTime = dateFormatter.date(from: oldTimeStr),
    let durationStr = dateComponentFormatter.string(from: oldTime, to: currentTime)
{
    print(durationStr) // 2 hrs
}

答案 1 :(得分:0)

希望这有帮助。编辑了maddy的建议。

    let currentTime = "11:00:04"
    let oldTime = "9:00:04"

    let currentTimeComponents = currentTime.components(separatedBy: ":")
    let oldTimeComponents = oldTime.components(separatedBy: ":")

    let hrsDifference = Int(currentTimeComponents[0])! - Int(oldTimeComponents[0])!
    let minutesDifference = Int(currentTimeComponents[1])! - Int(oldTimeComponents[1])!
    let secondsDifference = Int(currentTimeComponents[2])! - Int(oldTimeComponents[2])!

    print("hrsDifference = ",hrsDifference)
    print("minutesDifference = ",minutesDifference)
    print("secondsDifference = ",secondsDifference)