Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minutes between two times in swift

Tags:

ios

swift

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)

like image 433
Alex Avatar asked Jan 23 '18 11:01

Alex


3 Answers

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 and minute date components from the current and the converted date.
  • Calculate the difference with 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!
like image 108
vadian Avatar answered Nov 05 '22 11:11

vadian


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
   }
like image 17
Narasimha Nallamsetty Avatar answered Nov 05 '22 09:11

Narasimha Nallamsetty


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
like image 7
Reimond Hill Avatar answered Nov 05 '22 10:11

Reimond Hill