iosobjective-ccocoa-touchnsdatenscalendar

How to determine if an NSDate is today?


How to check if an NSDate belongs to today?

I used to check it using first 10 characters from [aDate description]. [[aDate description] substringToIndex:10] returns string like "YYYY-MM-DD" so I compared the string with the string returned by [[[NSDate date] description] substringToIndex:10].

Is there more fast and/or neat way to check?

Thanks.


Solution

  • In macOS 10.9+ & iOS 8+, there's a method on NSCalendar/Calendar that does exactly this!

    - (BOOL)isDateInToday:(NSDate *)date 
    

    So you'd simply do

    Objective-C:

    BOOL today = [[NSCalendar currentCalendar] isDateInToday:date];
    

    Swift 3:

    let today = Calendar.current.isDateInToday(date)