NSDate and DateByAddingComponents problem
-
28-10-2019 - |
سؤال
I'm dealing about this function on my application. I have to show some different graphics from different periods. The period is choose by swiping the current graph.
I have some trouble by using the DateComponents. When I'm testing the app, I show the Date edited by the dateByAddingComponents, and it looks like that in the Console:
Date : 2009-12-14 10:06:13 GMT
Date : 2009-11-13 10:06:13 GMT
Date : 2009-10-12 09:06:13 GMT
Date : 2009-09-11 09:06:13 GMT
Date : 2009-08-10 09:06:13 GMT
Date : 2009-07-09 09:06:13 GMT
Date : 2009-06-08 09:06:13 GMT
Date : 2009-05-07 09:06:13 GMT
Date : 2009-04-06 09:06:13 GMT
Date : 2009-03-05 10:06:13 GMT
Date : 2009-02-04 10:06:13 GMT
Date : 2009-01-03 10:06:13 GMT
Date : 2008-12-02 10:06:13 GMT
Date : 2008-11-01 10:06:13 GMT
Date : 2008-09-30 09:06:13 GMT
Date : 2008-08-29 09:06:13 GMT
as you can see, the hour's changing sometimes, but the biggest problem is that there miss a month (the 10th in the year 2008).
There is the code implemented for those actions :
if (currentPosition.x > gestureStartPoint.x) {
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
[dateComponents setDay:-1];
self.date = [gregorian dateByAddingComponents:dateComponents toDate:self.date options:0];
NSLog(@"Date : %@", date);
break;
case 1:
//NSLog(@"before : %@", date);
[dateComponents setMonth:-1];
self.date = [gregorian dateByAddingComponents:dateComponents toDate:self.date options:0];
NSLog(@"Date : %@", date);
break;
case 2:
//NSLog(@"before : %@", date);
[dateComponents setYear:-1];
self.date = [gregorian dateByAddingComponents:dateComponents toDate:self.date options:0];
NSLog(@"Date : %@", date);
break;
default:
break;
}
}
else if(currentPosition.x <= gestureStartPoint.x){
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
[dateComponents setDay:1];
self.date = [gregorian dateByAddingComponents:dateComponents toDate:self.date options:0];
NSLog(@"Date : %@", date);
break;
case 1:
[dateComponents setMonth:1];
self.date = [gregorian dateByAddingComponents:dateComponents toDate:self.date options:0];
NSLog(@"Date : %@", date);
break;
case 2:
[dateComponents setYear:1];
self.date = [gregorian dateByAddingComponents:dateComponents toDate:self.date options:0];
NSLog(@"Date : %@", date);
break;
default:
break;
}
}
How can I solve it???
المحلول
How can I solve it?
By being more careful. From the logs you show us it is clear that you are decrementing the date by 1 month and 1 day every time. So naturally, when you reach 2008-11-01, the next date is 2008-09-30.
The one-hour difference in the time is because of daylight savings time in your time zone.