Re: NSCalendar week-of-year calculations and week 1
Re: NSCalendar week-of-year calculations and week 1
- Subject: Re: NSCalendar week-of-year calculations and week 1
- From: Greg Parker <email@hidden>
- Date: Fri, 04 Jan 2013 17:38:22 -0800
On Jan 4, 2013, at 4:44 PM, Nick Zitzmann <email@hidden> wrote:
> Short question: Given a year, week-of-year, and weekday in that week-of-year, what is the most reliable way to get the NSDate for that day even when the week-of-year is week 1? This is calendrical grey area, because there may be two week 1s in a year.
Short answer: Use NSYearForWeekOfYearCalendarUnit.
> Long question:
>
> We're using the NSCalendar class to get an NSDate given a year, week-of-year, and weekday number. For weeks 2 through 52 of the Gregorian year, NSCalendar gives us the correct date.
>
> But this falls apart when the week-of-year number is week 1, because many years on the Gregorian calendar have two week 1s. In 2013 AD, there are two week 1s if the first weekday is on a Sunday - this week, and the last week of the year. So when I tell it to find the date corresponding to Sunday of week 1 of 2013, I want NSCalendar to return December 30, 2012. That is the first Sunday of the first week of 2013. However, it actually returns December 29, 2013. That date is the Sunday of the **other** week 1 of 2013, the one that is the first week of 2014.
>
> What do I have to set in NSDateComponents to give NSCalendar a little more context so I get the correct date number? I already tried setting the month to 1 (January) in the components, and I got the same incorrect results.
If you want to specify dates using weekday+week+year, you need to use NSYearForWeekOfYearCalendarUnit. yearForWeekOfYear is similar to year, except the yearForWeekOfYear boundaries are adjusted so that a yearForWeekOfYear never starts in the middle of a week.
For example, Monday December 31 2012 is:
year 2012, month 12, day 31
or
yearForWeekOfYear 2013, weekOfYear 1, weekday 2
(assuming firstWeekday is Sunday)
If your weekday+week+year specifications are coming from a human who doesn't know about yearForWeekOfYear, then you'll need to do a bit of wrangling to find the edge so you can translate year 2012 into yearForWeekOfYear 2013 when necessary. It may be useful to get January 1st 2013 via year+month+day and convert it to yearForWeekOfYear+weekOfYear+weekday (using -dateFromComponents: then -components:fromDate:). January 1st 2013's weekday value tells you how many of year 2012's days fall into yearForWeekOfYear 2013.
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
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