我正在尝试获取当月的开始和结束日期。这里有一些类似的问题,但我在使用它们时得到了意想不到的结果。这是我所做的:
NSDate *monthStart,*monthEnd;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [cal components:NSDayCalendarUnit fromDate:[NSDate date]];
[comps setDay:1];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
monthStart = [cal dateFromComponents:comps];
[comps setDay:[[NSCalendar currentCalendar]
rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:[NSDate date]].length];
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
monthEnd = [cal dateFromComponents:comps];
NSLog(@"%@",monthStart);
NSLog(@"%@",monthEnd);
不幸的是,输出是:
2012-12-24 15:39:28.159 Popup[1010:403] 0001-12-31 18:06:32 +0000
2012-12-24 15:39:28.160 Popup[1010:403] 0001-01-31 18:06:31 +0000
顺便说一句,我机器中配置的时区是 +5:30