i made small program calculate difference between 2 dates, , output number of days, , months passed. program shows number of months, , number of days fine, separately. however, when join them in flag, output shows right number of months, , "12" number of days, no matter date put in. i've tried inline components: (nsdaycalendarunit|nsmonthcalendarunit
), same problem occurs. here code. help!
#import <foundation/foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { nsdate *startdate=[nsdate datewithstring:@"2004-2-24 1:54:10 +0600"]; nsdate *today=[nsdate date]; nscalendar *gregorian = [[nscalendar alloc]initwithcalendaridentifier:nsgregoriancalendar]; nsuinteger flags = nsmonthcalendarunit | nsdaycalendarunit; nsdatecomponents *components = [gregorian components: flags fromdate:startdate todate:today options:0]; nsinteger days = [components day]; nsinteger months = [components month]; nslog(@"%li",(long)days); nslog(@"%li",(long)months); } return 0; }
output:
2013-05-05 14:49:36.943 calendercalc[4111:303] 12 2013-05-05 14:49:36.944 calendercalc[4111:303] 110
the output shows "12" number of days, no matter date put in.
are sure? when use startdate
of @"2013-4-30 1:54:10 +0600"
, see days
6 , months
0. code looks fine.
edit
here's how compare 2 dates' "day of month", regardless of whether or not they're in same month or year.
nscalendar* gregorian = [[nscalendar alloc]initwithcalendaridentifier:nsgregoriancalendar] ; nsdate* startdate = [nsdate datewithstring:@"2013-4-18 1:54:10 +0600"] ; nsdate* today = [nsdate datewithstring:@"2013-5-05 1:54:10 +0600"] ; nsdatecomponents* startdatecomponents = [gregorian components:nsdaycalendarunit fromdate:startdate] ; nsdatecomponents* todaycomponents = [gregorian components:nsdaycalendarunit fromdate:today] ; int daysapart = fabs(startdatecomponents.day - todaycomponents.day) ;
Comments
Post a Comment