Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing an NSDate to [NSDate date]

I am trying to force a user to select a date in the future with a date picker. I obviously used the compare: method, however, when I do the following code, even if it's the same date as [NSDate date], it tells the executes the if statement. Here is my code:

    if ([datePicker.date compare:[NSDate date]] == NSOrderedAscending) // If the picked date is earlier than today
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hmm, this date is earlier than today" 
                                                    message:@"The date you've selected is earlier than today's date, please pick another" 
                                                   delegate:nil  
                                          cancelButtonTitle:@"Okay, I'll pick another" 
                                          otherButtonTitles:nil];
    // Show the alert
    [alert show];

    // Release the alert
    [alert release];
}
like image 917
skylerl Avatar asked Feb 13 '10 19:02

skylerl


3 Answers

You can use

[datePicker.date timeIntervalSinceNow]

which returns an NSTimeInterval (just a typedef for a double, in units of seconds) which is positive for the future and negative for the past.

As the doc says, compare provides subsecond comparison, so you can use this to force their date to be a full day later (instead of just sometime in the future).

like image 116
Jesse Beder Avatar answered Sep 28 '22 04:09

Jesse Beder


I don't know the answer to your problem, but how you could circumvent it.

Just use the minimumDate property of the UIDatePicker, that's even a much cleaner approach.

like image 30
Georg Schölly Avatar answered Sep 28 '22 06:09

Georg Schölly


An NSDate object contains both a date AND a time, so there are MANY dates with the same day that can fall before or after another date with the same day.

The date class method returns a date object with the current date day AND time.

like image 33
gerry3 Avatar answered Sep 28 '22 05:09

gerry3