I'm trying to use [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:date]
on two different dates to see if they fall on the same day. However, if my time zone is different (say, somewhere in Germany), even though the dates are obviously the same, the days returned are different. If I use NSYearCalendarUnit
instead of NSEraCalendarUnit
on the same dates, the returned values are the same.
The only problem with using NSYearCalendarUnit
is it returns the same value for the same day of different years, and it's not simple to determine the number of days between two dates if they fall on different years.
Any ideas what's wrong or how to more easily determine if two dates are on the same day, or to determine the number of days between them?
Example:
[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Berlin"]];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date1 = [NSDate dateWithTimeIntervalSinceReferenceDate:300751200];
NSDate *date2 = [NSDate dateWithTimeIntervalSinceReferenceDate:300836062.388569];
NSLog(@"\nDate 1: %@\nDate 2: %@",date1,date2);
/*Output:
Date 1: 2010-07-14 00:00:00 +0200
Date 2: 2010-07-14 23:34:22 +0200
*/
int day1 = [cal ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit
forDate:date1];
int day2 = [cal ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit
forDate:date2];
NSLog(@"\nDay 1: %i\nDay 2: %i",day1,day2);
/*Output:
Day 1: 733966
Day 2: 733967
*/
day1 = [cal ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit
forDate:date1];
day2 = [cal ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit
forDate:date2];
NSLog(@"\nDay 1:%i\nDay 2: %i",day1,day2);
/*Output:
Day 1: 195
Day 2: 195
*/