Search code examples
iosobjective-cnsdate

Compare the month and day of two NSDates


I need to setup an if/else statement that compares only the month and day of two NSDates. One of the dates is selected with a UIDatePicker and the other would be today's date. If the month and date of the two are the same, something happens, if not something else happens.

This is how I currently have it set up, but it's not working (the else statement always fires). Not sure where to go from here:

.h

@interface ViewController : UIViewController {
    UIDatePicker *datePicker;
    NSDate *pickedDate;
    NSDateFormatter *pickedDateFormat;
    NSString *pickedDateString;
    NSDate *todaysDate;
    NSDateFormatter *todaysDateFormat;
    NSString *todaysDateString;
    UILabel *label;
}

.m

- (IBAction)buttonToCompareDates:(id)sender {
    // Sets date from date picker
    pickedDate = [datePicker date];
    pickedDateFormat = [[NSDateFormatter alloc] init];
    [pickedDateFormat setDateFormat:@"MM/dd"];
    pickedDateString = [pickedDateFormat stringFromDate:pickedDate];

    // Sets today's date
    todaysDate = [NSDate date];
    todaysDateFormat = [[NSDateFormatter alloc] init];
    [todaysDateFormat setDateFormat:@"MM/dd"];
    todaysDateString = [todaysDateFormat stringFromDate:todaysDate];

    // if/else statement 
    if (todaysDateString == pickedDateString) {
         label.text = @"The dates match.";
    } else { 
         label.text = @"The dates don't match.";
    }
}

I was under the assumption that this would work, but it doesn't. I only need to match the month and day sections of the NSDates, therefore I tried to format them down to those parts and compare the strings. Problem is, I always get the "The dates don't match." sentence, even when the dates do match. Not sure why, could use an explanation and the right way to go about this.


Solution

  • You have to use

    if ([todaysDateString isEqualToString:pickedDateString]) {
    

    instead of

    if (todaysDateString == pickedDateString) {
    

    Because you have to compare string contents instead of their pointers.

    Also you can optimize you implementation by using the same Date Formatter:

    - (IBAction)buttonToCompareDates:(id)sender {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM/dd"];
    
        // Sets date from date picker
        pickedDate = [datePicker date];
        pickedDateString = [dateFormatter stringFromDate:pickedDate];
    
        // Sets today's date
        todaysDate = [NSDate date];
        todaysDateString = [dateFormatter stringFromDate:todaysDate];
    
        // if/else statement 
        if ([todaysDateString isEqualToString:pickedDateString]) {
             label.text = @"The dates match.";
        } else { 
             label.text = @"The dates don't match.";
        }
    }