cocoa - Calculating the date of the first day of the week for a date in the first week of the year changes the month -


i need date first day of week date. code works fine, dates strange result. date first week of year converts last week's date:

nstimeinterval ti = 1420311299; nsdate* date = [nsdate datewithtimeintervalsince1970:ti];  nslog(@"%@", date); // output: 2015-01-03 18:54:59 +0000  nscalendar* calendar = [nscalendar currentcalendar]; nsdatecomponents *cmps = [calendar components:(kcfcalendarunitweekofyear | kcfcalendarunityear) fromdate:date];  cmps.weekday = calendar.firstweekday;  nslog(@"%@", cmps); // output:  calendar year: 2015                     //          week of year: 1                     //          weekday: 1    nsdate* newdate = [calendar datefromcomponents:cmps];  nslog(@"%@", newdate); // output: 2015-12-26 22:00:00 +0000 

the nscalendar class offers dedicated methods calculations this:

nsdate *date =...; nsdate *startoftheweek; nstimeinterval interval; [[nscalendar currentcalendar] rangeofunit:nscalendarunitweekofmonth                                 startdate:&startoftheweek                                   interval:&interval                                    fordate:date]; 

interval contains length of week. if don't need that, can pass in null.

nsdate *date =...; nsdate *startoftheweek; [[nscalendar currentcalendar] rangeofunit:nscalendarunitweekofmonth                                  startdate:&startoftheweek                                   interval:null                                   fordate:date]; 

to answer original question: weeks' starts , ends not aligned years'. 1st, 2nd, , 3rd of january might in 53rd week of previous year. 29th, 30th, 31st december might in 1st week of following year. rule is: if week's thursday in december, week belongs old year. if in january, week first week of new year.


every mac/ios developer should watch: wwdc 2011 video "session 117 - performing calendar calculations"


Comments