Reputation: 5053
I am using swift 5. I need to find out the (hour, minutes, second) between two string data. I have tried bellow code..
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)
Above code return 0. Please help me find out difference time in swift 5
Upvotes: 0
Views: 84
Reputation: 271575
You said you want the hours, minutes and seconds between the two dates, yet you are only getting the seconds components. The two dates are exactly 54 minutes and 0 seconds apart, so that's why you got 0.
You should only pass .hour, .minute, .second
, and print all three components:
let components = calendar1.dateComponents([.hour,.minute,.second], from: dateold, to: datenew)
print(components.hour!)
print(components.minute!)
print(components.second!)
Or, use a DateCompoenentFormatter
which formats the components for you:
let componentsFormatter = DateComponentsFormatter()
print("Idle time: \(componentsFormatter.string(from: components)!)")
Upvotes: 4