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

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts