Avatar ·

How to calculate the difference between two dates in months, days, hours, minutes, and seconds in Swift?

Hello! I'm new to Swift and can't figure out dates. I need to calculate the exact difference between two dates and display it in a readable format: how many months, days, hours, minutes, and seconds have passed. For example, between March 15, 2023, 10:30:00 and July 20, 2024, 14:45:30.

\n\n

I tried using Calendar and DateComponents, but I'm getting strange results. Here's my current code:

\n\n
import Foundation\n\nlet dateFormatter = DateFormatter()\ndateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"\nlet date1 = dateFormatter.date(from: "2023/03/15 10:30:00")!\nlet date2 = dateFormatter.date(from: "2024/07/20 14:45:30")!\n\nlet diff = date2.timeIntervalSince(date1)\nlet days = Int(diff) / 86400\nlet hours = (Int(diff) % 86400) / 3600\nlet minutes = (Int(diff) % 3600) / 60\nle