Minutes between two times in swift
Calendar
has powerful methods to do that.
Any explicit math with 60
, 3600
or even 86400
is not needed at all.
- Convert the time string to
Date
. - Get the
hour
andminute
date components from the current and the converted date. - Calculate the difference with
dateComponents(:from:to:
by specifying only theminute
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!
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
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
}