Get the difference between two dates in Swift
You might have understood the topic for today’s tutorial, “Getting the difference between two specific dates in Swift”.
As a programmer, you might need to do this as per the requirement, and also it is a very interesting task.
Calculate the difference between two dates in seconds
Suppose you need to find the difference between two given dates so we would define two date objects and then we will find the difference using Date.timeintervalSinceReferenceDate
as-
let mydate = DateFormatter() mydate.dateFormat = "yyyy/MM/dd HH:mm" let diwali = mydate.date(from: "2022/10/24 00:00") let newYear = mydate.date(from: "2023/01/01 00:00") let diffinSeconds = newYear!.timeIntervalSinceReferenceDate - diwali!.timeIntervalSinceReferenceDate print(diffinSeconds)
Output:
5961600.0
(We have taken two variables diwali and newYear. Diwali is a famous Indian festival)
The output is in seconds but sometimes there is a need to convert it into minutes, hours, days, months, and even years.
You can check: Get the Current Date and Time in Swift in every possible format
We can do this using the conversions manually. A year has 12 months, which has 4 weeks, a week has 7 days, which has 24 hours, and an hour consists of 60 minutes which in turn consists of 60 seconds.
The formulas to convert seconds into minutes-seconds/60
Calculate the difference between two dates in Minutes
The syntax for converting seconds into minutes-
let diffinMinutes=diffinSeconds/60 print(diffinMinutes)
Output:
99360.0
Calculate the difference between two dates in all the time units
Similarly, we can convert seconds into minutes, hours, days, weeks, months, and years using the code below:-
let mydate = DateFormatter() mydate.dateFormat = "yyyy/MM/dd HH:mm" let diwali = mydate.date(from: "2022/10/24 00:00") let newYear = mydate.date(from: "2023/01/01 00:00") let diffinSeconds = newYear!.timeIntervalSinceReferenceDate - diwali!.timeIntervalSinceReferenceDate let diffinMinutes=diffinSeconds/60 let diffinhours = diffinSeconds / (60.0 * 60.0) let diffindays = diffinSeconds / (60.0 * 60.0 * 24.0) let diffinweeks = diffinSeconds / (60.0 * 60.0 * 24.0 * 7.0) let diffinmonths = diffinSeconds / (60.0 * 60.0 * 24.0 * 30.4369) let diffinyears = diffinSeconds / (60.0 * 60.0 * 24.0 * 365.2422) print(diffinSeconds) print(diffinMinutes) print(diffinhours) print(diffindays) print(diffinweeks) print(diffinmonths) print(diffinyears)
Output:
5961600.0 99360.0 1656.0 69.0 9.857142857142858 2.2669851397481344 0.1889157386523244
So the task to count the difference between two dates has been successfully accomplished in Swift. You can use any of the above-mentioned conversions as per your requirement. I hope you liked this tutorial.
Leave a Reply