Re: NSCalendar/NSDate - generating all months/days in a year [SOLVED]
Re: NSCalendar/NSDate - generating all months/days in a year [SOLVED]
- Subject: Re: NSCalendar/NSDate - generating all months/days in a year [SOLVED]
- From: mmalc Crawford <email@hidden>
- Date: Mon, 22 Dec 2008 09:34:44 -0800
On Dec 22, 2008, at 8:47 AM, mmalc Crawford wrote:
There shouldn't be any need, though, to "add a month" for each
iteration, just start a new month with a date components object with
a new month number.
This could be made a little more efficient (and if you're not using
garbage collection, needs suitable memory management), but for the
sake of explicitness you could do something like the following.
mmalc
NSInteger specifiedYear = 2009;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE d MMMM y"];
NSLocale *locale = [NSLocale currentLocale];
dateFormatter.locale = locale;
NSCalendar *calendar = [locale objectForKey:NSLocaleCalendar];
NSDateComponents *yearStartComponents = [[NSDateComponents alloc] init];
[yearStartComponents setDay:1];
[yearStartComponents setMonth:1];
[yearStartComponents setYear:specifiedYear];
NSDate *yearStartDate = [calendar
dateFromComponents:yearStartComponents];
NSRange monthsRange = [calendar rangeOfUnit:NSMonthCalendarUnit
inUnit:NSYearCalendarUnit forDate:yearStartDate];
NSUInteger months = monthsRange.length;
NSUInteger month;
for (month = 1; month <= months; month++) {
NSDateComponents *monthStartComponents = [[NSDateComponents
alloc] init];
[monthStartComponents setDay:1];
[monthStartComponents setMonth:month];
[monthStartComponents setYear:specifiedYear];
NSDate *monthStartDate = [calendar
dateFromComponents:monthStartComponents];
NSRange daysRange = [calendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit forDate:monthStartDate];
NSUInteger days = daysRange.length;
NSUInteger day;
for (day = 1; day <= days; day++) {
NSDateComponents *dayComponents = [[NSDateComponents alloc]
init];
[dayComponents setDay:day];
[dayComponents setMonth:month];
[dayComponents setYear:specifiedYear];
NSDate *day = [calendar dateFromComponents:dayComponents];
NSString *dayString = [dateFormatter stringFromDate:day];
NSLog(@"dayString: %@", dayString);
}
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden