Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Thursday, December 12, 2013

Comparing Dates in iOS

So, you'd like to compare two NSDates in iOS, huh?

Date comparison is quite easy in Objective-C, but where it gets just a bit confusing is in the comparison result, which, when you are comparing two dates can be one of three values returned from the compare:(NSDate *)date method of NSDate: NSOrderedSame, NSOrderedAscending, and NSOrderedDescending.

Lets see a quick example:

  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:@"MM-dd-yyyy"];
  
  NSDate *date1 = [formatter dateFromString:@"01-01-2013"];
  NSDate *date2 = [formatter dateFromString:@"01-02-2013"];
  
  if([date1 compare:date2] == NSOrderedSame){
    NSLog(@"The dates are the same");
  } else if([date1 compare:date2] == NSOrderedAscending){
    NSLog(@"date1 is before date2");
  } else if([date1 compare:date2] == NSOrderedDescending){
    NSLog(@"date1 is after date2");
  }

>> date1 is before date2

And here it is in simpler terms (I think, at least), from the perspective of one of the dates:

[me compare:thatOtherDate];

NSOrderedSame - Me and that other date, we're the same.
NSOrderedAscending - I come before that other date.
NSOrderedDescending - I come after that other date.

I hope this helps you get things clear in your head, it certainly helps me to think of it this way.

Best of luck. And if you found this helpful, +1 this page, and it will be right at your fingertips to help you the next time you search for an answer to this question.




About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates