Question

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 ?

Was it helpful?

Solution

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"]]

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top