How to determine if an NSDate is today?

Seunghoon picture Seunghoon · Feb 25, 2010 · Viewed 70.4k times · Source

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.

Answer

Catfish_Man picture Catfish_Man · Mar 24, 2014

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)