Search code examples
iosnstimeinterval

NSTimeInterval in seconds between dates = nan


NSTimeInterval executionTime = [self.EndDownloadTime timeIntervalSinceDate:self.StartDownloadTime];
NSLog(@"Execution Time: %f", executionTime);

Result is always "nan". When i switch EndDownloadTime and StartDownloadTime, time is "0.00000"

StartDownloadTime and EndDownloadTime are types of NSDate.

How do i get the seconds between the two dates?

Thank you in advance.


Solution

  • The simplest solution is a better method, check the docs when things seem complicated:

    NSTimeInterval executionTime = [self.EndDownloadTime timeIntervalSinceDate:self.StartDownloadTime];
    

    When you are debugging a problem and everything looks correct but the code is failing then an assumption must be wrong. There are two assumptions here (at least): the values of self.EndDownloadTime and self.StartDownloadTime. NSLog them or use the debugger examining the values as you step through.

    Check everything:

    NSLog(@"StartDownloadTime: %@", self.StartDownloadTime);
    NSLog(@"StartloadTimeInterval: %f", [self.StartDownloadTime timeIntervalSince1970]);
    NSLog(@"EndDownloadTime: %@", self.EndDownloadTime);
    NSLog(@"EndDownloadTimeInterval: %f", [self.EndDownloadTime timeIntervalSince1970]);
    
    NSTimeInterval executionTime = [self.EndDownloadTime timeIntervalSince1970] - [self.StartDownloadTime timeIntervalSince1970];
    NSLog(@"Execution Time: %f", executionTime);
    

    Note: In Cocoa* properties and variables and method names by convention begin with a lower case letter, class names with an uppercase letter. This makes it easier for others to understand your code.