如何比较可可的两个日期(仅限日期;不是时间)?

abi*_*aja 9 macos cocoa objective-c

基本上,我想弄清楚它是否是第二天.因此,我将当前日期(例如1月2日)不断存储在plist中.但是下次用户打开应用程序时,如果日期已经改变(例如1月3日),我想做点什么.请注意,简单的升序检查不起作用,因为我不想知道一个日期是否晚于另一个日期,如果差异仅以小时为单位.我需要能够区分1月2日11:50和1月3日2:34而不是1月3日2:34和1月3日5:12.

Nie*_*tle 24

我使用以下内容找到了SO:

- (BOOL)isSameDay:(NSDate*)date1 otherDay:(NSDate*)date2 {
    NSCalendar* calendar = [NSCalendar currentCalendar];

    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];

    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];
}
Run Code Online (Sandbox Code Playgroud)