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.
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
}