Compare dates in swift
📆 No of days/years between two dates
Published in
2 min readFeb 18, 2023
Thought of writing this came to me when I was creating an all purpose Date helper utility. This will be a short article since the code is pretty much self explanatory.
Find number of days between two dates
let calendar = Calendar.current
guard let days = calendar.dateComponents([.day],
from: calendar.startOfDay(for: firstDate),
to: calendar.startOfDay(for: secondDate)).day else {
return
}
Find number of years between two dates
let calendar = Calendar.current
guard let result = calendar.dateComponents([.year], from: firstDate, to: secondDate).year else {
return
}
🎁Freebies
Find whether the given date is the current year
let present = Date?
if present {
let result = calendar.component(.year, from: inputDate) == calendar.component(.year, from: present)
}
Find whether the given date is yesterday
Here we have to find the number of days between the input date and today then check whether the result is equivalent to one. Let’s see the code.
/// 1) Finding the number of days between the input date and today
let calendar = Calendar.current
let today = Date!
guard let days = calendar.dateComponents([.day],
from: calendar.startOfDay(for: inputDate),
to: calendar.startOfDay(for: today)).day else {
return
}
/// 2) Check whether the result is equivalent to one
if days == 1 {
print("It was yesterday")
}
👷🏽 Here is the date helper utility I’m working on.