如何快速获得两个日期之间两个日期之间的时差(小时分钟秒)

时间:2019-12-12 07:21:20

标签: swift

我正在使用swift5。我需要找出两个字符串数据之间的(小时,分钟,秒)。我已经尝试了下面的代码。.

      var timestamp:String = "2019-12-12 01:01:02"
       var last_timestamp:String = "2019-12-12 01:55:02"

       let dateFormatter = DateFormatter()
       dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
       let dateold = dateFormatter.date(from: timestamp)!
       let datenew = dateFormatter.date(from: last_timestamp)!

       let calendar1 = Calendar.current
       let components = calendar1.dateComponents([.year,.month,.day,.hour,.minute,.second], from:  dateold, to:   datenew)
       let seconds = components.second
       print("seconds idle-->",seconds)

上面的代码返回0。请帮助我迅速找出差值时间

1 个答案:

答案 0 :(得分:4)

您说过您想要两个日期之间的小时,分​​钟和秒,但您只得到秒部分。这两个日期正好相距54分钟且 0秒,因此这就是为什么您得到0。

您应该只通过.hour, .minute, .second,并打印所有三个组件:

let components = calendar1.dateComponents([.hour,.minute,.second], from:  dateold, to:   datenew)
print(components.hour!)
print(components.minute!)
print(components.second!)

或者,使用DateCompoenentFormatter为您格式化组件:

let componentsFormatter = DateComponentsFormatter()
print("Idle time: \(componentsFormatter.string(from: components)!)")