35

I have objects of Date type.

I want to compare them, and I have written an if condition in the following way:

if (([startDate1 isEqualToDate:[self getDefaultDate]]) || (startDate1 != [ self getDefaultDate] && m_selectedDate >= m_currentDate1 && cycleStopped))
 {

///execute some condition

}

Am I right or wrong in this approach?

One more thing. Is this way right:

if (dtdate > [m_array objectatIndex:i]
{

}

Because I am getting random behavior.

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Ranjit
  • 4,576
  • 11
  • 62
  • 121
  • There's a method called compare: in the NSDate class reference that should help you. http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html – Luke Nov 18 '11 at 13:55
  • hey luke how can i check and "notequalto" condition – Ranjit Nov 18 '11 at 14:02
  • @Ranjit you can use the logical not operator with the same method call: `! [d1 isEqualToDate:d2]` – zekel Apr 12 '12 at 16:02

6 Answers6

84

Here's an example using the NSDate method, compare:

if([startDate compare: endDate] == NSOrderedDescending) // if start is later in time than end
{
    // do something
}

From the class reference:

If...

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.

You could also use the timeIntervalSinceDate: method if you wanted to compare two dates and find the seconds between them, for example.

EDIT:

if(([startDate1 compare:[self getDefaultDate]] == NSOrderedSame) || ([startDate1 compare: [self getDefaultDate]] != NSOrderedSame && (([m_selectedDate compare: m_currentDate1] == NSOrderedDescending) || [m_selectedDate compare: m_currentDate1] == NSOrderedSame) && cycleStopped))
Luke
  • 11,426
  • 43
  • 60
  • 69
  • Hey luke thanks for your information,but I am confused..can you show by converting my above if condition in your way.. so that it will be very helpful..thanks hey and one morething..whether earlier means greater or later means greater – Ranjit Nov 18 '11 at 14:18
  • @Ranjit NSDates work by amount of time, so bigger numbers are later dates. It's all in the class reference: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html – Aberrant Nov 18 '11 at 14:26
  • Updated again to fully take into account the last part; where m_selectedDate can either be equal or later to m_currentDate1. Just run through it and see how it goes :) – Luke Nov 18 '11 at 14:28
  • Hey Abberant ,I am keeping time components constants – Ranjit Nov 18 '11 at 14:32
  • Hey luke one more doubt What it I have condition like this id(dtdate >[m_array objectatIndex:i] then what shall i do – Ranjit Nov 18 '11 at 14:41
  • Using compare: you can either compare the dates to determine whether one is before, exactly equivalent to or ahead in time from the other. You need to decide which is best for your app. – Luke Nov 18 '11 at 15:06
  • ya that is ok...but suppose if I write if(date > [m_datearray objectatIndex:i]..wheteher this is the right way? – Ranjit Nov 19 '11 at 10:08
  • And when you compile it, what happens then? – Luke Nov 19 '11 at 10:58
  • I know this is old but im wondering if anyone thinks if NSORderedDescending and NSOrderedAscending should be reversed in this situation. I understand how it works but it doesnt seem logical to me. – Esko918 Apr 27 '15 at 17:15
  • So take the date 20150411 and 20150412. If I compare these 2 the outcome would be descending. So even though the second value is greater than the first value its considered descending when in my opinion shouldnt it be ascending cause the date is going up? – Esko918 Apr 27 '15 at 17:16
  • @Esko918 It's dependent on the order in which you compare the dates, eg - in my example, whichever date `startDate` and `endDate` correspond to will affect the outcome of the comparison. – Luke Apr 27 '15 at 18:54
  • @Luke ya but if im using today as a [todaysDate compare:laterDate] then it returns descending not ascending. i guess i see what your saying since im comparing the left hand value to the right hand value its descending from the right hand value. IDK seems like it should be the other way around but i get it – Esko918 Apr 27 '15 at 19:21
20

Easy way to compare NSDates (found here http://webd.fr/637-comparer-deux-nsdate):

#import <Foundation/Foundation.h>

@interface NSDate (Compare)

-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
//- (BOOL)isEqualToDate:(NSDate *)date; already part of the NSDate API

@end

And the implementation:

#import "NSDate+Compare.h"

@implementation NSDate (Compare)

-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
    return !([self compare:date] == NSOrderedAscending);
}

-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
    return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
    return ([self compare:date] == NSOrderedDescending);

}
-(BOOL) isEarlierThan:(NSDate*)date {
    return ([self compare:date] == NSOrderedAscending);
}

@end

Simple to use:

if([aDateYouWant ToCompare isEarlierThanOrEqualTo:[NSDate date]]) // [NSDate date] is now
{
    // do your thing ...
}

Enjoy

Pascal
  • 15,257
  • 2
  • 52
  • 65
7

I must admit that I find the "compare" == NSWhatHaveYou business too complicated to remember (even though it's correct and it works). NSDate has two other methods that my brain finds much easier to deal with: earlierDate and laterDate.

Consider this:

if ([myDate laterDate:today] == myDate) {
    NSLog(@"myDate is LATER than today");
} else {
    NSLog(@"myDate is EARLIER than today");
}

// likewise:
if ([myDate earlierDate:today] == myDate) {
    NSLog(@"myDate is EARLIER than today");
} else {
    NSLog(@"myDate is LATER than today");
}

Either method returns an NSDate object, which is either earlier or later than the other.

http://pinkstone.co.uk/how-to-compare-two-nsdates/

Jay Versluis
  • 2,062
  • 1
  • 19
  • 18
3

I really liked Luke's answer, and it worked like a charm.

I used something like this:

If ([enteredDate compare: [NSDate Date]]== NSOrderedSame || NSOrderedDescending)
{
 //Do Something if the enteredDate is later or the same as today
}else
{
//if the enteredDate is before today's date
}

I'm not sure if that helps, but just to reiterate what Luke had written.

Septronic
  • 1,156
  • 13
  • 32
1

This is a simple way to check if the date you think is larger (eg. in the future) compared to the date you think is earlier. Here is what this does.

  1. Gets the time interval (seconds and frac seconds) of both current and future date
  2. returns true if the date your testing is greater (time reference) the the other date

Here you go

- (BOOL)isDateGreaterThanDate:(NSDate*)greaterDate and:(NSDate*)lesserDate{

    NSTimeInterval greaterDateInterval = [greaterDate timeIntervalSince1970];
    NSTimeInterval lesserDateInterval = [lesserDate timeIntervalSince1970];

    if (greaterDateInterval > lesserDateInterval) 
        return YES;

    return NO;
}

This also works

BOOL *isGreaterDateTruelyGreater = [greaterDate timeIntervalSince1970] > [lesserDate timeIntervalSince1970];

The way objective-c deals with dates, is less than intuitive. Basically you can use NSTimeInterval to get the number of seconds from a point in time. It usually gives a long number, for instance as i am writing this 1351026414.640865 is the time interval from 1970.

Point in time > point in time 1351026415.640865 > 1351026414.640865 The above is 1 second ahead, so it is true.

Nelson Brian
  • 688
  • 6
  • 7
0

This link shows it in the best way:

http://www.myuiviews.com/2011/01/10/nsdate-comparison-which-is-older.html

cREcker
  • 2,323
  • 1
  • 16
  • 13