So I seem to be getting burned by the iPhone's calendar support again. I've come across an issue with the way core data compares dates. Core data appears to be storing dates using the Gregorian calendar as they come out in a 20XX-MM-dd format. But when I build an NSPredicate this way
[nsRequest setPredicate:[NSPredicate predicateWithFormat:@"publish <= %@ AND expires >= %@", [NSDate date], [NSDate date]]]
if the user's device isn't set to a Gregorian calendar then no items will appear, as core data doesn't seem to localizing it's NSDates before comparing against the input dates.
So it would appear that if the date were today '2011-05-31' in Japanese calendar mode core data is using '0023-05-31' since it's the 23rd year of the current emperor, placing the input date about 2000 years before what it's being compared against.
I've found I can work around this like so
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]] autorelease]];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSString *todayGregorian = [[dateFormat stringFromDate:[NSDate date]] retain];
[dateFormat release];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
[nsRequest setPredicate:[NSPredicate predicateWithFormat:@"publish <= %@ AND expires >= %@", [df dateFromString:todayGregorian], [df dateFromString:todayGregorian]]];
but I'm hoping that maybe I'm being an idiot and there's a better way. Any suggestions?
Please note:
- Asking my Japanese users to change the date format they use isn't an option.
- Also, I still need to store the core data dates in a Gregorian format, as these users do sometimes change their calendars back and forth.
Real problem My solution above is wrong. TechZen's answer kicked my head in to gear and I wish I could up vote him 100 times, I ended up solving the issue.
My problem is data going in to Core Data is being sent by the server in GMT and the formmater parsing that data might not necessarily be in GMT so I need to adjust the time going in to Core Data correctly.