ios - How can I get the monday of a week in a special date in Objective-C? -


e.g. 01.10.2010 friday => 27.09.2010 monday.

i have no idea how manage one. btw: how can calculate dates?

for time/date calculations use nsdatecomponents.

listing 2 getting sunday in current week

nsdate *today = [[nsdate alloc] init]; nscalendar *gregorian = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar];  // weekday component of current date nsdatecomponents *weekdaycomponents = [gregorian components:nsweekdaycalendarunit fromdate:today];  /* create date components represent number of days subtract current date. weekday value sunday in gregorian calendar 1, subtract 1 number of days subtract date in question.  (if today's sunday, subtract 0 days.) */ nsdatecomponents *componentstosubtract = [[nsdatecomponents alloc] init]; [componentstosubtract setday: 0 - ([weekdaycomponents weekday] - 1)];  nsdate *beginningofweek = [gregorian datebyaddingcomponents:componentstosubtract todate:today options:0];  /* optional step: beginningofweek has same hour, minute, , second original date (today). normalize midnight, extract year, month, , day components , create new date components. */ nsdatecomponents *components =     [gregorian components:(nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit)                fromdate: beginningofweek]; beginningofweek = [gregorian datefromcomponents:components]; 

march 2014

actually there smarter way

nscalendar *cal = [nscalendar currentcalendar]; [cal setfirstweekday:2];    //2 monday. 1:sunday .. 7:saturday don't set it, if user's locale should determine start of week nsdate *now = [nsdate date]; nsdate *monday; [cal rangeofunit:nsweekcalendarunit  // want have start of week        startdate:&monday             // write date object monday         interval:null                // don't care seconds week has          fordate:now];               // want monday of today's week 

if change weekday represents start of week (sunday vs. monday), should change after snippet.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -