I want to check if the month and day of the birth date are equivalent to the current day and month.
The above solutions, while useful for comparing Date
s in other senses, won't really do what you say you want to do; that is, determine if a month and day in a different year is the same month and day as today.
Instead, what you need is this:
extension Date {
func isSameDayAndMonth(as date: Date) -> Bool {
let cal = Calendar.current
let compare = cal.dateComponents([.year, .month, .day], from: self, to: date)
//returns how many years, months and days between self and the given date
//year will be different, of course,
//but we want no difference between month and day
return compare.month == 0 && compare.day == 0
}
}
Usage:
import Foundation
let cal = Calendar.current
let today = Date.now //20 April 2022
var bday: Date
//different month, different day
bday = cal.date(from: DateComponents(year: 1970, month: 8, day: 17))!
print(bday.isSameDayAndMonth(as: today)) //false
//same month, different day
bday = cal.date(from: DateComponents(year: 1970, month: 4, day: 30))!
print(bday.isSameDayAndMonth(as: today)) //false
//different month, same day
bday = cal.date(from: DateComponents(year: 1970, month: 3, day: 20))!
print(bday.isSameDayAndMonth(as: today)) //false
//same month, same day
bday = cal.date(from: DateComponents(year: 1970, month: 4, day: 20))!
print(bday.isSameDayAndMonth(as: today)) //true