NSCalendar月份范围

时间:2013-09-10 12:59:15

标签: ios nscalendar

此代码

NSDateComponents *component = [[NSDateComponents alloc] init];
NSCalendar       *gregorian = [[NSCalendar alloc]   initWithCalendarIdentifier:NSGregorianCalendar];
[component setMonth:1];
[component setYear:2013];
[component setDay:1];
currentMonth = [gregorian dateFromComponents:component];
NSLog(@"Date in MonthView %@ ",currentMonth);

给我以下日期

Date in MonthView 2012-12-31 23:00:00 +0000

为什么呢?月份范围应该从0到11?

2 个答案:

答案 0 :(得分:5)

不,几个月从1到12.这可能是因为您的设备/ PC的时区。设置timezine,你应该有你期望的日期

[component setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]

答案 1 :(得分:0)

实际上,答案可能取决于您使用的日历(我看到您使用的是Gregorian,但您的用户可能没有)。

了解给定日期组件范围的最安全方法是查询日历。另请注意,它可能会有所不同(例如,格里历日历中的最小范围是1-28,而最大值是1-31)。

NSRange minimumMonthRange = [yourCalendar minimumRangeOfUnit:NSMonthCalendarUnit];

原始答案

根据“日期和时间编程指南”中的示例:

  

[...]年份单位是2004年,月份单位是5,日期单位是6(公历是2004年5月6日)。

由于飞蛾去了1月,2月,3月,4月,5月......并且他们使用5月5日,我会说月份的范围是1到12。