0

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

Enamul Haque
  • 4,789
  • 1
  • 37
  • 50
  • maybe it is because 02 seconds - 02 seconds = 0? check other properties, components.minute will return 54 – Alexandr Kolesnik Dec 12 '19 at 07:28
  • try this : https://stackoverflow.com/questions/27182023/getting-the-difference-between-two-nsdates-in-months-days-hours-minutes-seconds – riddhi Dec 12 '19 at 07:28
  • Because you have equal seconds in `timestamp` and `last_timestamp`. If you want to get only seconds change `calendar1.dateComponents([.year, .month, .day, .hour, .minute, .second], from: dateold, to: datenew)` to `calendar1.dateComponents([.second], from: dateold, to: datenew)` – Ruben Nahatakyan Dec 12 '19 at 07:29

1 Answers1

4

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)!)")
Sweeper
  • 213,210
  • 22
  • 193
  • 313