0

I have a current time and a static time (eg - yesterday 9.30 pm), I need to find the time difference between these two times in hh:mm:ss format.

This is the code I used to get the current time:

let date = Date()
let calendar = Calendar.current

let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")
Arasuvel
  • 2,953
  • 1
  • 28
  • 40
Arun
  • 701
  • 10
  • 26

2 Answers2

4

try this:-

    let dateFormatter = DateFormatter()
    var userCalendar = Calendar.current
    userCalendar.timeZone = TimeZone.current
    let requestedComponent: Set<Calendar.Component> = [.hour,.minute,.second]
    dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss"
    let startTime = Date()
    let endTime = dateFormatter.date(from: "28/08/17 08:40:00")
    let timeDifference = userCalendar.dateComponents(requestedComponent, from: endTime!, to: startTime)
    print(timeDifference)
    let date = Calendar(identifier: .gregorian).date(from: timeDifference)
    dateFormatter.dateFormat = "HH:mm:ss"
    let dateString =  dateFormatter.string(from: date!)

    print(dateString)

you can change format according to your requirement.

Pushpendra
  • 926
  • 6
  • 13
0
let date = Date()
let cal = Calendar.current
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
let staticTime = ...
let comps = cal.dateComponents([.hour, .minute, .second], from: date, to: staticTime)
let diff = cal.date(from: comps)!
let diffString = formatter.string(from: diff)
Chandler De Angelis
  • 2,538
  • 6
  • 31
  • 45
  • Hi, i amgetting an error as "type of expression is ambiguous without more context " in let comps = cal.dateComponents([.hour, .minute, .second], from: date, to: staticTime) – Arun Aug 29 '17 at 06:51
  • You need to instantiate the `statcTime` variable to a `Date` – Chandler De Angelis Aug 29 '17 at 06:56