NSCalendar months range

空扰寡人 提交于 2019-12-11 06:04:00

问题


This code

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);

gives to me the following date

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

Why? The months range is supposed to go from 0 to 11 ?


回答1:


No, months go from 1 to 12. That's probably because the timezone of your device/PC. Set the timezine and you should have the date as you expect

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



回答2:


Actually, the answer may depend on the calendar you are using (I see that you are using Gregorian but your users may not).

The safest way to know the range for a given date component is to query the calendar for it. Also note that it may vary (for example the minimum range of days in a gregorian calendar is 1-28 while the maximum is 1-31).

NSRange minimumMonthRange = [yourCalendar minimumRangeOfUnit:NSMonthCalendarUnit];

Original answer

From on of the examples in the "Date and Time Programming Guide":

[...] the year unit is 2004, the month unit is 5, and the day unit is 6 (in the Gregorian calendar this is May 6th, 2004).

Since the moths go Jan, Feb, Mar, Apr, May, ... and they use 5 for May I would say that the range of months is 1 to 12.



来源:https://stackoverflow.com/questions/18719644/nscalendar-months-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!