I got a string "14:05"
How could I compare it with current time and get time difference in minutes?
Difference may be both negative and positive(current time is before string or after)
Calendar
has powerful methods to do that.
Any explicit math with 60
, 3600
or even 86400
is not needed at all.
Date
.hour
and minute
date components from the current and the converted date.dateComponents(:from:to:
by specifying only the minute
component.let time = "14:05"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let timeDate = dateFormatter.date(from: time)!
let calendar = Calendar.current
let timeComponents = calendar.dateComponents([.hour, .minute], from: timeDate)
let nowComponents = calendar.dateComponents([.hour, .minute], from: Date())
let difference = calendar.dateComponents([.minute], from: timeComponents, to: nowComponents).minute!
For getting minutes difference between two dates I have done like below.
You can keep this method in common class and call.
func getMinutesDifferenceFromTwoDates(start: Date, end: Date) -> Int
{
let diff = Int(end.timeIntervalSince1970 - start.timeIntervalSince1970)
let hours = diff / 3600
let minutes = (diff - hours * 3600) / 60
return minutes
}
Despite all the answers, I found Narashima's one the most straight forward. However, here there is a more straightforward one.
let startDate = Date()
let endDate = Date(timeInterval: 86400, since: startDate)
let diffSeconds = Int(endDate.timeIntervalSince1970 - startDate.timeIntervalSince1970)
let minutes = diffSeconds / 60
let hours = diffSeconds / 3600
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With