Search code examples
objective-cxcodensdatensdatecomponentsnstimeinterval

iOS: problem with NSDate and NSDateComponent


NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setTimeZone:[ NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ] ;
[components setYear:2011];
[components setDay:13];
[components setMonth:5];
NSDate *date1 = [gregorianCalendar dateFromComponents:components];
NSDate *date2 = [[NSDate alloc] init];


    NSTimeInterval diff = [data2 timeIntervalSinceDate:date1];
    NSString *intervalString = [NSString stringWithFormat:@"%f", diff];
    int second = [intervalString intValue];
    int period = second/3600/24; 
    NSLog(@"period:%d", period);
    NSLog(@"date1:%@", data1);
    NSLog(@"date2:%@", data2);

In consol the result is:

2011-05-12 10:57:00.406 Project[297:707] period:0;

2011-05-12 10:57:00.375 Project[297:707] data2:2011-05-12 08:56:52 +0000

2011-05-12 10:57:00.402 Project[297:707] data1:2011-05-13 00:00:00 +0000

I don't understand why period is "0", it must be "1"; Can you help me?


Solution

  • NSTimeInterval is just a double, so you shouldn't need to convert it to a string then back to an int.

    What happens if you do something like this:

    NSTimeInterval diff = [data2 timeIntervalSinceDate:date1];
    int period = (int)diff/3600/24; 
    NSLog(@"period:%d", period);
    

    Also if the interval is diff is less than 3600*24 the result of diff/3600/24 will be less than 1, so the int value will be flattened to 0.