Re: NSCalendar and the number of days in a week in a month?
Re: NSCalendar and the number of days in a week in a month?
- Subject: Re: NSCalendar and the number of days in a week in a month?
- From: Greg Herlihy <email@hidden>
- Date: Mon, 08 May 2006 07:31:39 -0700
- Thread-topic: NSCalendar and the number of days in a week in a month?
Every week has 7 days, no matter when it falls. What you are really asking
is which day of the week does the 1st of a particular month fall.
For example, create the date for the first of November, 2006.
NSCalendarDate *date = [NSCalendarDate dateWithYear:2006 month:11 day:1
hour:0 minute:0 second:0 timeZone:[NSTimeZone defaultTimeZone]];
Ask which day of the week this date falls on:
int dayOfWeek = [date dayOfWeek];
The result is 3 (Wednesday). Subtract the day of the week from 7 to
determine the number of days in the "first week" of November 2006:
int daysInFirstWeek = 7-dayOfWeek;
And the final answer is 7 - 3 or 4 days for the first week of November 2006.
Of course if the first day of the week is not Sunday, then the program will
have to adjust the arithmetic accordingly.
Greg
On 5/8/06 6:59 AM, "Nick Zitzmann" <email@hidden> wrote:
> How do I, using NSCalendar, obtain the number of days in a given week
> in a given month? I'm trying to figure out how to count the number of
> days in the first week of a given month, and I can't seem to figure
> it out. Here's what I'm trying:
>
> NSDateComponents *firstSaturdayOfCurrentMonth = [[NSDateComponents
> alloc] init];
> int numberOfDaysInFirstWeekOfMonth;
>
> [firstSaturdayOfCurrentMonth setEra:[currentDateComponents era]];
> [firstSaturdayOfCurrentMonth setYear:[currentDateComponents year]];
> [firstSaturdayOfCurrentMonth setMonth:[currentDateComponents month]];
> [firstSaturdayOfCurrentMonth setWeek:1];
> [firstSaturdayOfCurrentMonth setWeekday:7];
> numberOfDaysInFirstWeekOfMonth = [[calendar
> components:NSDayCalendarUnit fromDate:[calendar
> dateFromComponents:firstSaturdayOfCurrentMonth]] day];
> [firstSaturdayOfCurrentMonth release];
>
> ...where currentDateComponents is an NSDateComponents object that has
> already been initialized and set to the components of a given date
> using NSCalendar.
>
> My method returns the correct amount of days in the first week of May
> 2006 (6), but returns the incorrect number for November 2006 (it
> returns 6 when there's really 4). I also tried using -
> rangeOfUnit:inUnit:forDate: and it always returned 7 as a length.
>
> Nick Zitzmann
> <http://www.chronosnet.com/>
>
>
> _______________________________________________
> Do not post admin requests to the list. They will be ignored.
> Cocoa-dev mailing list (email@hidden)
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden