Reputation: 12219
I am using below method to add or subtract days from an NSDate.
When I logged the values I get an unexpected result at times.
Here is one of the case:
//This adds X days to the current Date and returns to the user
+(NSDate*)getRelativeDateInDays:(NSInteger)days forDate:(NSDate*)date{
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [[NSDateComponents alloc] init];
[weekdayComponents setDay:days];
NSDate *newDate = [gregorian dateByAddingComponents:weekdayComponents toDate:date options:0];
[gregorian release];
[weekdayComponents release];
NSLog(@"start Date : %@ End Date %@",date,newDate);
return newDate; }
CASE 1:
2012-02-17 06:28:14.474 Application[2906:707] start Date : 2012-03-08 11:26:23 +0000 End Date 2012-03-09 11:26:23 +0000 Number of days 1
CASE 2:
2012-02-17 06:29:00.631 Application[2906:707] start Date : 2012-03-10 11:26:23 +0000 End Date 2012-03-11 10:26:23 +0000 Number of days 1
In case 1, when I added a single day to 2012-03-08 11:26:23 +0000, I get 2012-03-09 11:26:23 +0000.
But when I add a single day to 2012-03-10 11:26:23 +0000 I get 2012-03-11 10:26:23 +0000.
1 hour is additionally reduced. What could be the problem here? Is any one have faced this problem?
Upvotes: 0
Views: 1602
Reputation: 8536
It's because of daylight savings times - US daylight savings starts on 11th March.
Edit:
You can solve it by converting the inputted date into a date components object, change the day component (time is unaffected) and then convert back into an NSDate
.
Upvotes: 2