iphone - NSDate get a specific day of the week? -


i hope learning curve i'm going through.

i create arbitrary date. want find saturday following third friday.

    nslog(@"date: %@", [date description]);     nscalendar *calendar = [nscalendar currentcalendar];     nstimezone *zone = [nstimezone timezonewithname:@"est"];     [calendar settimezone:zone];     nsdatecomponents *components = [calendar components:(nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit) fromdate:date];     [components setweekday:6];        // 1 = sunday ... 7 = saturday     [components setweekdayordinal:3]; // 3rd friday     resultdate = [calendar datefromcomponents:components];     nslog(@"date: %@", [resultdate description]); 

and output:

date: 2010-11-01 05:00:00 gmt

date: 2010-11-01 05:00:00 gmt

why? how can fix this?

change components to:

(nsweekdaycalendarunit | nsyearcalendarunit) 

this works:

 nsdate *today = [[nsdate alloc] init];  nslog([today description]);   nscalendar *gregorian = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar];   nsdatecomponents *weekdaycomponents = [gregorian components:(nsweekdaycalendarunit | nsweekdayordinalcalendarunit) fromdate:today];   nsdatecomponents *componentstosubtract = [[nsdatecomponents alloc] init];  [componentstosubtract setday: 0 - ([weekdaycomponents weekday])];  [componentstosubtract setweekdayordinal:([weekdaycomponents weekday] <= 6) ? 3 : 4];  //[componentstosubtract setweekdayordinal:3]; //old way - not perfect   nsdate *saturday = [gregorian datebyaddingcomponents:componentstosubtract todate:today options:0];   nsdatecomponents *components =  [gregorian components:(nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit)      fromdate: saturday];  saturday = [gregorian datefromcomponents:components];   nslog([saturday description]); 

hope helps.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -