objective c - Difference between NSDate and NSDateComponent value for the same date -
i created simple function first , last day of week day in it. looking @ nslog output found different values returned nsdate descriptor , component day same date, why ?
here nslog outputs:
nsdate: 2011-04-03 22:00:00 +0000, day component: 4 nsdate: 2011-04-09 22:00:00 +0000, day component: 10
as can see, nsdate 3 of april , day component 4 first row, , respectively 9 , 10 second one.
here code:
nsdate *date = [nsdate date]; //today april 5th 2011 nscalendar *cal =[[nscalendar alloc]initwithcalendaridentifier:nsgregoriancalendar]; [cal setfirstweekday:2]; //my week starts monday //define beginning of week nsdate *beginningofweek = nil; [cal rangeofunit:nsweekcalendarunit startdate:&beginningofweek interval:nil fordate:date]; nsdatecomponents *begincomponents = [cal components:(nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit | nsweekcalendarunit | nsweekdaycalendarunit) fromdate:beginningofweek]; //define end of week, 6 days offset beginning nsdatecomponents *offset = [[nsdatecomponents alloc]init]; [offset setday:6]; nsdate *endofweek = [cal datebyaddingcomponents:offset todate:beginningofweek options:0]; nsdatecomponents *endcomponents = [cal components:(nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit | nsweekcalendarunit | nsweekdaycalendarunit) fromdate:endofweek]; nslog(@"nsdate: %@, day component: %d",beginningofweek, [begincomponents day]); nslog(@"nsdate: %@, day component: %d",endofweek, [endcomponents day]);
your dates being printed timezone of +0000 (utc), while nscalendar instance (and therefore nsdatecomponents) using device's default timezone (which guess utc+2).
Comments
Post a Comment