raj raj - 4 years ago 112
Swift Question

Want to find out the difference between the two times on button title

SWIFT:
Click here to see the imageI am having the times on two button on its title I am having the two time with AM/PM.
I have tried so many ways to subtract the times between these two buttons but not successful.
Please suggest me the proper way as the how to subtract the IN time and OUT time and get the TOTAL HOUR as a result only in hours.
Please help.

Answer Source

You can use Calendar method dateComponents to calculate how many hours there is between two dates. You can use DateFormatter to get the dates from your strings:

let start = "09:35 PM"
let end = "09:36 AM"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"

if let startDate = dateFormatter.date(from: start),
    let endDate = dateFormatter.date(from: end) {
    let hours = Calendar.current.dateComponents([.hour], from: startDate, to: endDate < startDate ? Calendar.current.date(byAdding: .day, value: 1, to: endDate) ?? endDate : endDate).hour ?? 0
    print(hours)  // 12
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download