How To Check If Two Dates Are From The Same Day In Swift

I want to know if two dates are from the same day!

How To Check If Two Dates Are From The Same Day In Swift

Here’s a quick function to check if two dates are from the same day:

func isSameDay(date1: Date, date2: Date) -> Bool {
    let diff = Calendar.current.dateComponents([.day], from: date1, to: date2)
    if diff.day == 0 {
        return true
    } else {
        return false
    }
}

Of course you change the date components from .day to .year or .month to check if the dates are from the same month or year.

How To Check If Two Dates Are From The Same Month In Swift

func isSameDay(date1: Date, date2: Date) -> Bool {
    let diff = Calendar.current.dateComponents([.month], from: date1, to: date2)
    if diff.day == 0 {
        return true
    } else {
        return false
    }
}

How To Check If Two Dates Are From The Same Year In Swift

func isSameDay(date1: Date, date2: Date) -> Bool {
    let diff = Calendar.current.dateComponents([.year], from: date1, to: date2)
    if diff.day == 0 {
        return true
    } else {
        return false
    }
}
If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts