hello all,
This is my programming problem: I need to be able to determine the number of hours and the number of minutes that are the difference between two times. My attempt to solve this problem used this code:
However, the problem is that this code finds only the difference between two times in a single day. If I try to find the difference between two times for two different days then the code produces the wrong answer.
For example, let's say that I wish to find the difference between 23:00 (European/Military time presentation style) of today and 01:00 of tomorrow (again the same presentation style). Then the answer produced would be 22 hours and 0 minutes instead of 2 hours and 0 minutes.
I am not very familiar with macOS/UNIX handling of timestamps and datestamps and it seems to challenge even experienced programmers.
Can someone suggest the correct strategy to solve my problem? Thank you
This is my programming problem: I need to be able to determine the number of hours and the number of minutes that are the difference between two times. My attempt to solve this problem used this code:
Code:
let time = "02:05"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let timeDate = dateFormatter.date(from: time)!
let tcalendar = Calendar.current
let timeComponents = tcalendar.dateComponents([.hour, .minute], from: timeDate)
let nowComponents = tcalendar.dateComponents([.hour, .minute], from: Date())
let differenceMinutes = tcalendar.dateComponents([.hour, .minute], from: timeComponents, to: nowComponents)
However, the problem is that this code finds only the difference between two times in a single day. If I try to find the difference between two times for two different days then the code produces the wrong answer.
For example, let's say that I wish to find the difference between 23:00 (European/Military time presentation style) of today and 01:00 of tomorrow (again the same presentation style). Then the answer produced would be 22 hours and 0 minutes instead of 2 hours and 0 minutes.
I am not very familiar with macOS/UNIX handling of timestamps and datestamps and it seems to challenge even experienced programmers.
Can someone suggest the correct strategy to solve my problem? Thank you