Question

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?

Was it helpful?

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.

OTHER TIPS

date2 is the current date. No idea why period should be one here.

At the time of this writing, diff is approx. -53000. Dividing it brings it to zero as you get and is expected.

Also keep in mind that NSTimeInterval is a floating point number, and you are converting it through a string to an integer, which will drop off the fractions.

And there is no point in doing this conversion through a string - just use int seconds = (int) diff;.

Please copy/paste your code directly, as you refer to data1and data2, but your variables are called date1 and date2. But then, this might already be your bug, if those variables are declared elsewhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top