Search code examples
iosswiftdebuggingnsdate

Swift - How to check if an NSDate is yesterday compare to current time?


I have an NSDate value. I need to check (compare to system current time) if that is yesterday or not. I thought that was easy because I could just pull the day value out of my NSDate and +1 to compare it. But soon afterward, I realized it's an inappropriate idea because what if it's end of the month, let's say July 31. And next day is not July 32, is August 1.

What's the most effective way to check if an NSDate is yesterday (compare to current time)?


Solution

  • As of iOS 8.0, you can use -[NSCalendar isDateInYesterday:], like this:

    let calendar = NSCalendar.autoupdatingCurrentCalendar()
    
    let someDate: NSDate = some date...
    if calendar.isDateInYesterday(someDate) {
        // It was yesterday...
    }
    

    If you'll be doing this a lot, you should create the calendar once and keep it in an instance variable, because creating the calendar object is not trivial.