I have a class that holds an start date and an end date, normally initialised to the firt and last second of the month.
The following function works correctly going from Nov 2010 forwards into December and back again however going backwards from November ends up with startDate set to
2010-09-30 23:00:00 GMT
Ie. a month and an hour ago.
Strangely the endDate is still correctly set to
2010-11-01 00:00:00 GMT
And going forward a month from this incorrect date also results in the correct time and date.
Is this a bug or am I doing something I shouldn't be ?
-(void) moveMonth:(NSInteger)byAmount { // Positive or negative number of months NSCalendar *cal = [NSCalendar currentCalendar]; NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease]; // Update the start date [components setMonth:byAmount]; NSDate *newStartDate = [cal dateByAddingComponents:components toDate:[self startDate] options:0]; [self setStartDate:newStartDate]; // And the end date [components setMonth:1]; NSDate *newEndDate = [cal dateByAddingComponents:components toDate:[self startDate] options:0 ]; [self setEndDate:newEndDate]; }
SOLUTION: Answer correctly pointed out this is a DST issue
If you want to deal in absolute times and date then using the following avoids any DST being involved.
NSCalendar *cal = [[NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"GMT"]; [cal setTimeZone:zone];