How to check if two NSDates are from the same day [duplicate]

☆樱花仙子☆ 提交于 2019-12-02 21:39:36

NSCalendar has a method that does exactly what you want actually!

/*
    This API compares the Days of the given dates, reporting them equal if they are in the same Day.
*/
- (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2 NS_AVAILABLE(10_9, 8_0);

So you'd use it like this:

[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2];

Or in Swift

Calendar.current.isDate(date1, inSameDayAs:date2)
Mike Henderson

You should compare the date components:

let date1 = NSDate(timeIntervalSinceNow: 0)
let date2 = NSDate(timeIntervalSinceNow: 3600)

let components1 = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: date1)
let components2 = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: date2)

if components1.year == components2.year && components1.month == components2.month && components1.day == components2.day {
    print("same date")
} else {
    print("different date")
}

Or shorter:

let diff = Calendar.current.dateComponents([.day], from: self, to: date)
if diff.day == 0 {
    print("same day")
} else {
    print("different day")
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!