问题
I'm using a NSDate that is incremented/decremented thanks to NSDateCompoments:
dateComponents = [[NSDateComponents alloc] init];
self.date = [gregorian dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];
...
[dateComponents setDay:1];
self.date = [gregorian dateByAddingComponents:dateComponents toDate:self.date options:0];
[dateComponents setDay:0];
Now, I want to set the day to set the NSDate to the first of the month (and the first month of the year too), but I dont know how to do
Thanks a lot!!!
EDIT:
NSDateComponents *dateComponentsSetFirst = [gregorian components:( NSYearCalendarUnit |
NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:self.date];
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
requestTy = @"hours";
break;
case 1:
requestTy = @"days";
NSLog (@"avant %@",self.date);
[dateComponents setDay:1];
self.date = [gregorian dateFromComponents:dateComponentsSetFirst];
[dateComponents setDay:0];
NSLog (@"après %@",self.date);
break;
case 2:
requestTy = @"months";
NSLog (@"before %@",self.date);
[dateComponents setMonth:1];
self.date = [gregorian dateFromComponents:dateComponentsSetFirst];
[dateComponents setMonth:0];
NSLog (@"after : %@",self.date);
break;
default:
break;
}
give me
2011-08-17 11:23:34.365 e-mars[20942:207] avant 2011-08-17 09:23:30 GMT
2011-08-17 11:23:34.366 e-mars[20942:207] après 2011-08-16 22:00:00 GMT
when I pass in the case 1 !
and
2011-08-17 11:26:05.747 e-mars[20942:207] before 2011-08-16 22:00:00 GMT
2011-08-17 11:26:05.747 e-mars[20942:207] after : 2011-08-16 22:00:00 GMT
when I pass in the case 2 !
回答1:
You are not adding components to a date. You simply initialize the dateComponents from a given date, set the day and month (and year if you want) and then get the dateFromComponents. Apple Date and Time Programming Guide
NSDateComponents *dateComponents = [gregorian components:( NSYearCalendarUnit |
NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:[NSDate date]];
[dateComponents setDay:1];
[dateComponents setMonth:1];
self.date = [gregorian dateFromComponents:dateComponents];
来源:https://stackoverflow.com/questions/7089720/set-the-first-of-the-month-of-a-nsdate