Alexander MacLeod - 1 year ago 92

Swift Question

I have two times that I would like to calculate the difference in minutes between them. They are as follows:

`startDate = "23:51"`

endDate = "00:01"

They are both of type

`String`

`Date`

`NSCalendar`

`extension Date {`

func minutes(from date: Date) -> Int {

return Calendar.current.components(.minute, from: date, to: self, options: []).minute ?? 0

}

}

However this produces the incorrect result as the days, months, etc. are unknown. How would I accomplish this?

Answer Source

Here's a pretty basic way to find the difference without using `NSDate`

:

```
let startDate = "23:51"
let endDate = "00:01"
let startArray = startDate.componentsSeparatedByString(":") // ["23", "51"]
let endArray = endDate.componentsSeparatedByString(":") // ["00", "01"]
let startHours = Int(startArray[0])! * 60 // 1380
let startMinutes = Int(startArray[1])! + startHours // 1431
let endHours = Int(endArray[0])! * 60 // 0
let endMinutes = Int(endArray[1])! + endHours // 1
var timeDifference = endMinutes - startMinutes // -1430
let day = 24 * 60 // 1440
if timeDifference < 0 {
timeDifference += day // 10
}
```

And at the end `timeDifference`

equals `10`

.

This function is assuming that the end date will take place after the start date no matter what. So if the end date is a time that is before the start date it will add 1440 minutes (1 day). It also assumes that the dates are in the format "hh:mm" where the hours range from 0 to 24 and minutes range from 0 to 60.