Calculating the Difference Between Two Time Periods in Swift
Swift is the go-to language for iOS and macOS development. When working with scheduling, alarms, or timers in an app, you'll often need to calculate the difference between two time periods.
Swift provides powerful tools in the Foundation
framework to handle date and time with precision.
In this sub-article, we’ll write a Swift program that calculates the difference between two time values using DateComponents
. The logic is based on the approach from our C lead article, tailored to Swift's concise and readable syntax.
Required Framework
Ensure you import the Foundation
module to use date and time utilities:
import Foundation
This is included by default in most Swift environments.
Swift Program: Calculate the Difference Between Two Time Periods
// DIFFERENCE BETWEEN TWO TIME PERIODS in Swift using Foundation
import Foundation
// Step-1 Define a date formatter
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// Step-2 Create start and end time using the formatter
let startTime = formatter.date(from: "2025-09-01 08:10:00")!
let endTime = formatter.date(from: "2025-09-09 13:55:40")!
// Step-3 Calculate the time interval between the two dates
let interval = endTime.timeIntervalSince(startTime)
// Step-4 Convert the interval (in seconds) to hours, minutes, and seconds
let totalSeconds = Int(interval)
let hours = totalSeconds / 3600
let minutes = (totalSeconds % 3600) / 60
let seconds = totalSeconds % 60
// Step-5 Print the time difference
print("\nTIME DIFFERENCE: \(hours) HOURS, \(minutes) MINUTES, \(seconds) SECONDS")
Output
TIME DIFFERENCE: 205 HOURS, 45 MINUTES, 40 SECONDS
Explanation
-
DateFormatter
converts string representations of dates intoDate
objects. -
The
timeIntervalSince
method returns the time difference in seconds. -
We convert the seconds to hours, minutes, and seconds for easy interpretation.
This method is well-suited for Swift applications involving date calculations, UI countdowns, or event duration measurements.
???? Extra Metric: Duration in Days
You can also compute and display the total number of days:
let days = hours / 24
print("TOTAL DAYS: \(days)")
Output
TOTAL DAYS: 8
This metric is helpful for time spans longer than 24 hours
, such as for travel itineraries, billing, or project tracking.