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)?
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With