0

In my application I need to compare three dates in one if-else cycle. I have a start date, end date and the date of testing. What I want to check is whether the test date is between the start date and end date.

if (testDate >= startDate && testDate <= endDate) {

If I set the startDate to 25/04/2012 and the endDate to 24/04/2019 and the testDate to 25/12/2013 the code works. But if i set the startDate to 26/04/2000 and the endDate to 24/04/2019 and the testDate to 25/12/2013 the code does not works. What's wrong?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Andrea
  • 427
  • 3
  • 16

2 Answers2

3

You cannot sanely compare Objective-C objects with any boolean operators in C. You'd be comparing their addresses, not their values.

Look at the documentation for the NSDate class, specifically the -compare: method.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
2

Dates can be compared like that. However, you must first call timeIntervalSince1970 to convert the date to an integer type value. In this case, it gives you a numeric value of type NSTimeInterval.

The other option is to use the compare: method invoked on the NSDate object.

In that case, comparing one date to another will give a result detailed in the class reference as follows:

  • The receiver and anotherDate are exactly equal to each other, NSOrderedSame

  • The receiver is later in time than anotherDate, NSOrderedDescending

  • The receiver is earlier in time than anotherDate, NSOrderedAscending.

Max MacLeod
  • 26,115
  • 13
  • 104
  • 132