Andrew
Andrew

Reputation: 141

NSDate returns different answers

I'm grabbing the current date and comparing it to a predefined date, however I'm having an issue where the string is different sometimes. My code:

NSDate *todaysDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateToday = [dateFormatter stringFromDate:todaysDate];
NSLog(@"%@", dateToday);

Sometimes I'll get 'Dec 30, 2013' - sometimes 'Dec 30 2013' (no comma) and sometimes '30 Dec 2013'. I cannot see why this would happen.

Any thoughts?

EDIT: Responding to questions asked. I'm simply trying to see if the current date is the same as a predefined date, or if it's beyond that date. My code for this is:

if ([dateToday  isEqual: @"30 Dec 2013"]) {
    //It's the day of the event, run the day view
    [self performSegueWithIdentifier:@"mainToDay" sender:self];
} else if ([todaysDate timeIntervalSinceDate:postEventDate] > 0) {
    //It's after the event, run the post event screen
    [self performSegueWithIdentifier:@"mainToPost" sender:self];
}

I was simply using the log to see what was returned then emulating it. I didn't realise it would change. :)

Cheers.

Upvotes: 0

Views: 67

Answers (2)

rmaddy
rmaddy

Reputation: 318794

Using a date style will result in one of many possible strings based on the user's locale and language. There are better approaches. If you really want to compare against a hardcoded date string, at least do the following:

NSDate *todaysDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *dateToday = [dateFormatter stringFromDate:todaysDate];

if ([dateToday isEqualToString:@"2013-12-30"]) {
}

This ensures a consistent format and eliminates any language specific text.

Upvotes: 0

coneybeare
coneybeare

Reputation: 33101

This can happen if the language or locale of the test device changes, but it should be consistent when there are no changes.

UPDATE

Check some of the functions in these libraries, makes you life a ton easier. I use Erica Saduns in my apps. She has a isEqualToDateIgnoringTime which seems exactly like what you are looking for.

Upvotes: 2

Related Questions