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

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

    I like progrmr's solution, but I would go even further and make a category of NSDate that provides this method. It will make your code slightly more readable, and you won't need to copy and paste the method into each new class that might need it – just import the header file.

    NSDate+SameDay.h

    @interface NSDate (SameDay)
    - (BOOL)isSameDayAsDate:(NSDate*)otherDate;
    @end
    

    NSDate+SameDay.m

    #import "NSDate+SameDay.h"
    
    @implementation NSDate (SameDay)
    
    - (BOOL)isSameDayAsDate:(NSDate*)otherDate {
    
        // From progrmr's answer...
        NSCalendar* calendar = [NSCalendar currentCalendar];
    
        unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
        NSDateComponents* comp1 = [calendar components:unitFlags fromDate:self];
        NSDateComponents* comp2 = [calendar components:unitFlags fromDate:otherDate];
    
        return [comp1 day]   == [comp2 day] &&
               [comp1 month] == [comp2 month] &&
               [comp1 year]  == [comp2 year];
    }
    
    @end
    

    Then, after importing NSDate+SameDay.h in your class, you can use it like so:

    if ([myFirstDate isSameDayAsDate:mySecondDate]) {
        // The two dates are on the same day...
    }
    

提交回复
热议问题