Search code examples
iosnsdateunix-timestampnstimeintervaldifference

Find difference between two timestamps - iOS


I am trying to use NSTimeInterval to figure out the difference between two timestamps in my iOS application. However I when trying to pass in my timestamp, I get the following error:

Bad receiver type 'double'

Here is my code:

// Get the current date/time in timestamp format.
NSString *timestamp = [NSString stringWithFormat:@"%f", [[NSDate new] timeIntervalSince1970]];
double current = [timestamp doubleValue];

// Find difference between current timestamp and
// the timestamp returned in the JSON file.
NSTimeInterval difference = [current timeIntervalSinceDate:1296748524];

I thought that NSTimeInterval is just a another meaning for double.. is it not?

Note that '1296748524' is just being used here as a test.

I don't understand what I am doing wrong.

Thanks for you're time :)


Solution

  • I recognize that timestamp! If you're going to get a timestamp as a string, and then convert it back to a double, you can just get it as a double.

    Fix:

    NSString *timestamp = [NSString stringWithFormat:@"%f", [[NSDate new] timeIntervalSince1970]];
    double current = [timestamp doubleValue];
    NSTimeInterval difference = [[NSDate dateWithTimeIntervalSince1970:current] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:1296748524]];
    
    NSLog(@"difference: %f", difference);
    

    Better:

    double currentt = [[NSDate new] timeIntervalSince1970];
    NSTimeInterval differ= [[NSDate dateWithTimeIntervalSince1970:currentt] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:1296748524]];
    NSLog(@"differ: %f", differ);
    

    But what you're really doing is converting a date to a timestamp to a string to a timestamp to a date to a timestamp, so why not just use that from the beginning and use:

    Best:

    double timeStampFromJSON = 1296748524; // or whatever from your JSON
    double dif = [[NSDate date] timeIntervalSince1970] - timeStampFromJSON;
    NSLog(@"dif: %f", dif);
    

    All will be same result.