Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 938
Tom Xue Avatar asked Aug 07 '16 03:08

Tom Xue


2 Answers

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.

like image 184
rob mayoff Avatar answered Oct 16 '22 09:10

rob mayoff


In Swift 3/4/5 the API has changed:

Calendar.current.isDateInToday(yourDate)
Calendar.current.isDateInYesterday(yourDate)
Calendar.current.isDateInTomorrow(yourDate)

To get the current date:

let now = Date()
like image 21
KlimczakM Avatar answered Oct 16 '22 08:10

KlimczakM