15

With the iOS SDK I need to find an easy and secure way to see if an NSDate is today, yesterday, tomorrow. What I'm looking for is something like this in pseudo code:

NSDate *myDate = someDate;
if ([myDate isTomorrow]) {
    NSLog("Tomorrow"); 
}

How would you solve it?

mrrmatinsi
  • 283
  • 1
  • 6
  • 11
  • possible duplicate of [Compare NSDate for Today or Yesterday](http://stackoverflow.com/questions/2893835/compare-nsdate-for-today-or-yesterday) – martin clayton Oct 29 '10 at 14:08

3 Answers3

41

I understand that this is pretty old, but I want to bring the answer up to date (as I didn't see anyone else post a more up to date answer).

Since iOS 8.0 you have a bunch of functions that you can use for date comparison:

  • compareDate:toDate:toUnitGranularity:
  • isDate:equalToDate:toUnitGranularity:
  • isDate:inSameDayAsDate:
  • isDateInToday:
  • isDateInTomorrow:
  • isDateInWeekend:
  • isDateInYesterday:

See below example:

NSDate *today = [NSDate new];
NSCalendar* calendar = [NSCalendar currentCalendar];

BOOL isToday = [calendar isDateInToday:today];
BOOL isYesterday = [calendar isDateInYesterday:today];

isToday will be YES.

isYesterday will be NO, given that we gave it todays date.

See Apple's Documentation for further reading.

Mark
  • 480
  • 4
  • 11
33

Check our Erica Sadun's great NSDate extension class: http://github.com/erica/NSDate-Extensions

There are lots of date comparisons, among them exactly what you need :)

Nekto
  • 17,837
  • 1
  • 55
  • 65
runmad
  • 14,846
  • 9
  • 99
  • 140
  • Found out after playing with this a little that it seems to have some issues, for example with daylight saving also the dateBysubstractingDays isn't working. It is a great extension but not always that fail safe. – mrrmatinsi Nov 26 '10 at 14:40
  • 1
    For those who will be reading comments: project has been already updated several times so don't worry, everything should work fine. – Nekto Oct 30 '12 at 03:44
  • 2
    Erica's code was *exactly* what I was searching for and a great utility category for NSDate. Highly recommended. – Jerry Brady Jan 21 '13 at 16:08
  • This is pretty old, but anyone reading this should consider using a combination of NSCalendar and NSDateComponents instead of using these interval macros in this utility. NSCalendar takes care of those computations for you and handles edge cases properly. – drhr Dec 30 '13 at 22:47
4

Swift 3

let isToday = Calendar.current.isDateInToday(yourDate)

You can then check the value and proceed accordingly with simply:

if isToday {
    //If true, do this
}

There are similar functions for tomorrow, weekend, and a few others, for example:

let isTomorrow = Calendar.current.isDateInTomorrow(yourDate)

This guide has them all in Objective-C and Swift:

enter image description here

Dave G
  • 12,042
  • 7
  • 57
  • 83