Search code examples
iphonensdatenstimeinterval

To find the difference between two times


I want to get the difference between two times.

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setCurrentQuestion];
}


-(void)setCurrentQuestion{

    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    startTime = [dateFormatter stringFromDate:[NSDate date]];
    date1 = [dateFormatter dateFromString:startTime];

    [self answerTapped];  
}

-(void)answerTapped{
            endtime = [dateFormatter stringFromDate:[NSDate date]];
            date2 = [dateFormatter dateFromString:endtime];
            [dateFormatter release];
            dateFormatter = nil;

            NSTimeInterval * timeDifference =[date2 timeIntervalSinceDate:date1];


}

I am using this code to get the difference between start time and end time, but I am getting the error as " Inintializing 'NSTimeInterval *' (aka 'double ') with an expression of incompatible type 'NSTimeInterval' (aka 'double') " at "NSTimeInterval * timeDifference =[date2 timeIntervalSinceDate:date1]; " line. What this error means? How to resolve this? Or Please tell me how will I get the time difference? Please help.


Solution

  • Its the asterisk. You are declaring timeDifference as a pointer to an NSTimeInterval. It's just a double as you correctly point out. Just change to:

    NSTimeInterval timeDifference =[date2 timeIntervalSinceDate:date1];
    

    Also, I think your dates and strings are getting released too early. The simplest thing to do is to declare properties for your dates. For pre-ARC:

    @property (retain, nonatomic) NSDate * date1;
    @property (retain, nonatomic) NSDate * date2; 
    

    or for ARC:

    @property (strong, nonatomic) NSDate * date1;
    @property (strong, nonatomic) NSDate * date2; 
    

    Then assign with a dot operator like this:

    self.date1 = [NSDate date];
    

    You don't need those strings at all.