3

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

因此,例如说 currentTime = 11:00:04 和 oldTime = 9:00:04 然后我想要 durationOfTime = 2hr's。

现在就是这样,我有一个代码可以获取时间并将其存储在上面的格式中。但是,我在这里尝试不同的代码时遇到了各种问题,这些问题与时间长度有关。

4

2 回答 2

2

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

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
}
于 2018-05-03T03:14:56.163 回答
0

希望这会有所帮助。编辑了麦迪的建议。

    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)
于 2018-05-03T03:16:10.723 回答