NSCalendar: Problem getting weeks in a month...

Posted by AngrySpade on Stack Overflow See other posts from Stack Overflow or by AngrySpade
Published on 2010-03-14T17:31:45Z Indexed on 2010/03/14 17:35 UTC
Read the original article Hit count: 470

Filed under:
|
|

I am creating a calendar control of sorts...

One thing I need to know is how many weeks are there in a Month...

So NSCalendar rangeOfUnit:inUnit:forDate Seems to be exactly what I need...

Except I am noticing something that seems off and I can't quite figure out why this is happening...

The following code...

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2010];
[dateComponents setDay: 1];

for (int x=1; x<=12; x++)
{
    [dateComponents setMonth: x];

    NSDate *date = [calendar dateFromComponents:dateComponents];
    NSLog(@"Date: %@", date);

    NSRange range = [calendar rangeOfUnit: NSWeekCalendarUnit
                                   inUnit: NSMonthCalendarUnit
                                  forDate:date];

    NSLog(@"%d Weeks in Month %d", range.length, [dateComponents month]);

}

Is returning the following debug messages...

2010-03-14 13:08:10.350 Scrap[4256:207] Date: 2010-01-01 00:00:00 -0500

2010-03-14 13:08:10.351 Scrap[4256:207] 5 Weeks in Month 1

2010-03-14 13:08:10.352 Scrap[4256:207] Date: 2010-02-01 00:00:00 -0500

2010-03-14 13:08:10.352 Scrap[4256:207] 4 Weeks in Month 2

2010-03-14 13:08:10.353 Scrap[4256:207] Date: 2010-03-01 00:00:00 -0500

2010-03-14 13:08:10.353 Scrap[4256:207] 5 Weeks in Month 3

2010-03-14 13:08:10.354 Scrap[4256:207] Date: 2010-04-01 00:00:00 -0400

2010-03-14 13:08:10.355 Scrap[4256:207] 5 Weeks in Month 4

2010-03-14 13:08:10.356 Scrap[4256:207] Date: 2010-05-01 00:00:00 -0400

2010-03-14 13:08:10.357 Scrap[4256:207] 5 Weeks in Month 5

2010-03-14 13:08:10.358 Scrap[4256:207] Date: 2010-06-01 00:00:00 -0400

2010-03-14 13:08:10.358 Scrap[4256:207] 5 Weeks in Month 6

2010-03-14 13:08:10.359 Scrap[4256:207] Date: 2010-07-01 00:00:00 -0400

2010-03-14 13:08:10.360 Scrap[4256:207] 5 Weeks in Month 7

2010-03-14 13:08:10.361 Scrap[4256:207] Date: 2010-08-01 00:00:00 -0400

2010-03-14 13:08:10.364 Scrap[4256:207] 5 Weeks in Month 8

2010-03-14 13:08:10.364 Scrap[4256:207] Date: 2010-09-01 00:00:00 -0400

2010-03-14 13:08:10.365 Scrap[4256:207] 5 Weeks in Month 9

2010-03-14 13:08:10.366 Scrap[4256:207] Date: 2010-10-01 00:00:00 -0400

2010-03-14 13:08:10.366 Scrap[4256:207] 5 Weeks in Month 10

2010-03-14 13:08:10.367 Scrap[4256:207] Date: 2010-11-01 00:00:00 -0400

2010-03-14 13:08:10.367 Scrap[4256:207] 5 Weeks in Month 11

2010-03-14 13:08:10.369 Scrap[4256:207] Date: 2010-12-01 00:00:00 -0500

2010-03-14 13:08:10.369 Scrap[4256:207] 52 Weeks in Month 12

I cant quite figure out why I get 52 weeks in month 12.

Any clues?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about iphone