How to determine if an NSDate is today?

前端 未结 20 2087
礼貌的吻别
礼貌的吻别 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 18:40

    I would try to get today's date normalized to midnight and the second date, normalize to midnight then compare if it is the same NSDate.

    From an Apple example here's how you normalize to midnight today's date, do the same for the second date and compare:

    NSCalendar * gregorian = [[NSCalendar alloc]
                                   initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents * components =
        [gregorian components:
                     (NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit)
                     fromDate:[NSDate date]];
    NSDate * today = [gregorian dateFromComponents:components];
    

提交回复
热议问题