dateByAddingComponents problem and getting difference of dates with NSDateComponents problem!

Posted by Rob on Stack Overflow See other posts from Stack Overflow or by Rob
Published on 2010-03-25T01:07:06Z Indexed on 2010/03/25 1:13 UTC
Read the original article Hit count: 519

Filed under:
|
|

I am having problems with adding values to dates and also getting differences between dates. The dates and components calculated are incorrect.

So for adding, if I add 1.5 months, I only get 1 month, however if I add any whole number ie (1 or 2 or 3 and etc) it calculates correctly.

Float32 addAmount = 1.5;

NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setMonth:addAmount];

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
 [gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

 NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:Date1 options:0];

Now for difference, if I have a date that has been added with exactly one year (almost same code as above), it adds correctly, but when the difference is calculated, I get 0 years, 11 months and 30 days.

NSDate *startDate = Date1;
   NSDate *endDate = Date2;

   NSCalendar *gregorian = [[NSCalendar alloc]
          initWithCalendarIdentifier:NSGregorianCalendar];
   [gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

   NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;

   NSDateComponents *components = [gregorian components:unitFlags
              fromDate:startDate
                toDate:endDate options:0];

   NSInteger years = [components year];
   NSInteger months = [components month];
   NSInteger days = [components day];

What am I doing wrong? Also I have added the kCFCalendarComponentsWrap constanct in the options for both adding and difference functions but with no difference.

Thanks

© Stack Overflow or respective owner

Related posts about iphone

Related posts about nscalendar