Cocoa-Touch: How do I see if two NSDates are in the same day?

后端 未结 12 652
走了就别回头了
走了就别回头了 2020-11-30 04:35

I need to know if two NSDate instances are both from the same day.

Is there an easier/better way to do it than getting the NSDateComponents and comparing day/month/y

12条回答
  •  暖寄归人
    2020-11-30 05:01

    If you are targeting iOS 8 (and OS X 10.9) or later, then Joe's answer is a better solution using a new method in NSCalendar just for this purpose:

    -[NSCalendar isDate:inSameDayAsDate:]
    

    For iOS 7 or earlier: NSDateComponents is my preference. How about something like this:

    - (BOOL)isSameDayWithDate1:(NSDate*)date1 date2:(NSDate*)date2 {
        NSCalendar* calendar = [NSCalendar currentCalendar];
    
        unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
        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];
    }
    

提交回复
热议问题