设置 NSDate 的第一个月 [英] Set the first of the month of a NSDate
问题描述
由于 NSDateCompoments,我正在使用递增/递减的 NSDate:
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];
现在,我想设置日期将 NSDate 设置为一个月的第一天(以及一年的第一个月),但我不知道该怎么做
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
非常感谢!!!
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;
}
给我
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
当我传入案例 1 时!
when I pass in the case 1 !
和
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
当我传入案例 2 时!
when I pass in the case 2 !
推荐答案
您没有向日期添加组件.您只需从给定日期初始化 dateComponents,设置日期和月份(如果需要,还可以设置年份),然后获取 dateFromComponents.苹果日期和时间编程指南
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];
这篇关于设置 NSDate 的第一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!