Calculating the difference in hours between two dates in Swift

Published by donnywals on

Sometimes you need to calculate the difference between two dates in a specific format. For instance, you might need to know the difference between dates in hours. Or maybe you want to find out how many days there are between two dates. One approach for this would be to determine the number of seconds between two dates using timeIntervalSince:

let differenceInSeconds = lhs.timeIntervalSince(rhs)

You could use this difference in seconds to convert to hours, minutes or any other unit you might need. But we can do better in Swift using DateComponents. Given two dates, you can get the difference in hours using the following code:

let diffComponents = Calendar.current.dateComponents([.hour], from: startDate, to: endDate)
let hours = diffComponents.hour

The hour property on diffComponents will give you the number of full hours between two dates. This means that a difference of two and a half hours will be reported as two.

If you're looking for the difference between two dates in hours and minutes, you can use the following code:

let diffComponents = Calendar.current.dateComponents([.hour, .minute], from: lhs, to: rhs)
let hours = diffComponents.hour
let minutes = diffComponents.minute

If the dates are two and a half hours apart, this would give you 2 for the hour component, and 30 for the minute component.

This way of calculating a difference is pretty smart. If you want to know the difference in minutes and seconds, you could use the following code:

let diffComponents = Calendar.current.dateComponents([.minute, .second], from: lhs, to: rhs)
let minutes = diffComponents.minute
let seconds = diffComponents.second

Considering the same input where the dates are exactly two and a half hours apart, this will give you 150 for the minute component and 0 for the second component. It knows that there is no hour component so it will report 150 minutes instead of 30.

You can use any date component unit for this time of calculation. Some examples include years, days, nanoseconds and even eras.

Date components are a powerful way to work with dates and I highly recommend using this approach instead of doing math with timeIntervalSince because DateComponents are typically far more accurate.

If you have questions or feedback about this tip, feel free to shoot me a Tweet.


Practical Combine

Learn everything you need to know about Combine and how you can use it in your projects with my new book Practical Combine. You'll get thirteen chapters, a Playground and a handful of sample projects to help you get up and running with Combine as soon as possible.

The book is available as a digital download for just $24.99!

Get Practical Combine

Receive weekly updates about my posts

Categories: Quick Tip