ios - How to make an NSCalendar week begin on Monday instead of Sunday -
when try make current weeks date show in log (monday sunday) it's week starts sunday. example: week wee 38. yesterday 20th of september. code did show days monday sunday correct. today (21th of september) log shows next weeks dates (week 39) when it's still week 38.
my code:
nsdate *currentdate = [nsdate date]; nscalendar *mycalendar = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar]; nsdatecomponents *currentcomps = [mycalendar components:( nsyearcalendarunit | nsmonthcalendarunit | nsweekofyearcalendarunit | nsweekdaycalendarunit | nshourcalendarunit | nsminutecalendarunit) fromdate:currentdate]; int thisweeksnumber = currentcomps.weekofyear; nslog(@"1 %d", thisweeksnumber); [currentcomps setweekday:2]; nsdate *firstdayoftheweek = [mycalendar datefromcomponents:currentcomps]; nsdate *seconddayoftheweek = [self datebyaddingdays:1 todate:firstdayoftheweek]; nsdate *thirddayoftheweek = [self datebyaddingdays:2 todate:firstdayoftheweek]; nsdate *fourthdayoftheweek = [self datebyaddingdays:3 todate:firstdayoftheweek]; nsdate *fifthdayoftheweek = [self datebyaddingdays:4 todate:firstdayoftheweek]; nsdate *sixthdayoftheweek = [self datebyaddingdays:5 todate:firstdayoftheweek]; nsdate *seventhdayoftheweek = [self datebyaddingdays:6 todate:firstdayoftheweek]; nsdateformatter *mydateformatter = [[nsdateformatter alloc] init]; mydateformatter.dateformat = @"yyyy-mm-dd"; nsstring *firststr = [mydateformatter stringfromdate:firstdayoftheweek]; nsstring *secondstr = [mydateformatter stringfromdate:seconddayoftheweek]; nsstring *thirdstr = [mydateformatter stringfromdate:thirddayoftheweek]; nsstring *fourthstr = [mydateformatter stringfromdate:fourthdayoftheweek]; nsstring *fifthstr = [mydateformatter stringfromdate:fifthdayoftheweek]; nsstring *sixthstr = [mydateformatter stringfromdate:sixthdayoftheweek]; nsstring *seventhstr = [mydateformatter stringfromdate:seventhdayoftheweek]; nslog(@"\n %@ \n %@ \n %@ \n %@ \n %@ \n %@ \n %@", firststr, secondstr, thirdstr, fourthstr, fifthstr, sixthstr, seventhstr); }
and nsdate method:
- (nsdate*)datebyaddingdays:(nsinteger)days todate:(nsdate *)date { nscalendar *calendar = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar]; nsdatecomponents *comps = [[nsdatecomponents alloc] init]; comps.day = days; return [calendar datebyaddingcomponents: comps todate: date options: 0]; }
this should display week 38 days display next week dates because it's sunday. (as i'm writing it's week 38 , 21th of september)
you need call setfirstweekday: nsuinteger
parameter value of 2
(sunday 1
)
[mycalendar setfirstweekday:2];
Comments
Post a Comment