How to determine if an NSDate is today?

前端 未结 20 2013
礼貌的吻别
礼貌的吻别 2020-11-28 18:20

How to check if an NSDate belongs to today?

I used to check it using first 10 characters from [aDate description]. [[aDate descriptio

20条回答
  •  失恋的感觉
    2020-11-28 19:04

    Refer to Apple's documentation entry entitled "Performing Calendar Calculations" [link].

    Listing 13 on that page suggests that to determine the number of midnights between days, you use:

    - (NSInteger)midnightsFromDate:(NSDate *)startDate toDate:(NSDate *)endDate
    {
        NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
        NSInteger startDay = [calendar ordinalityOfUnit:NSDayCalendarUnit
                                                 inUnit:NSEraCalendarUnit
                                                forDate:startDate];
        NSInteger endDay = [calendar ordinalityOfUnit:NSDayCalendarUnit
                                               inUnit:NSEraCalendarUnit
                                              forDate:endDate];
        return endDay - startDay;
    }
    

    You may then determine if two days are the same by using that method and seeing if it returns 0 or not.

提交回复
热议问题