How to determine if an NSDate is today?

前端 未结 20 2091
礼貌的吻别
礼貌的吻别 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条回答
  •  旧时难觅i
    2020-11-28 18:50

    No need to juggle with components, eras and stuff.

    NSCalendar provides an method to get the beginning of a certain time unit for an existing date.

    This code will get the begin of today and another date and compare that. If it evaluates to NSOrderedSame, both dates are during the same day — so today.

    NSDate *today = nil;
    NSDate *beginningOfOtherDate = nil;
    
    NSDate *now = [NSDate date];
    [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&today interval:NULL forDate:now];
    [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfOtherDate interval:NULL forDate:beginningOfOtherDate];
    
    if([today compare:beginningOfOtherDate] == NSOrderedSame) {
        //otherDate is a date in the current day
    }
    

提交回复
热议问题