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

后端 未结 12 670
走了就别回头了
走了就别回头了 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:15

    The following will test whether two dates represent the same day in a given era (which is sufficient in many cases):

    - (BOOL)isDate:(NSDate *)date1 sameDayAsDate:(NSDate *)date2 {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        int diff = [calendar ordinalityOfUnit:NSDayCalendarUnit 
                                       inUnit:NSEraCalendarUnit 
                                      forDate:date1] -
                   [calendar ordinalityOfUnit:NSDayCalendarUnit 
                                       inUnit:NSEraCalendarUnit 
                                      forDate:date2];
        return 0 == diff;
    }
    

提交回复
热议问题