-2

I am calculating the time difference between two NSDates and it always returns 0.0000 .I am using the Same logic to calculate the time stamp and have formatted correctly as well .. When I try to log the dates separately , it gets printed correctly and when I print the difference, It prints 0.0000... Here's the code to calculate the date ..

-(NSDate *) toLocalTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: [NSDate date]];
return [NSDate dateWithTimeInterval: seconds sinceDate: [NSDate date]];
}

and here's the code where I find the difference..

NSLog(@"the time when the location was updated is %@",timeWhenTheLocationWasUpdated);
NSLog(@"the time when the server was contacted last time was %@",timeWhenLastLocationPosted);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss ZZZ"];
NSDate *timeofUpdatingLocation = [[NSDate alloc] init];
NSDate *timeofPostingToTheServer = [[NSDate alloc]init];
timeofUpdatingLocation = [dateFormatter dateFromString:timeWhenTheLocationWasUpdated];
timeofPostingToTheServer = [dateFormatter dateFromString:timeWhenLastLocationPosted];
NSTimeInterval difference = [timeofPostingToTheServer timeIntervalSinceDate:timeofUpdatingLocation];
NSLog(@"the difference between posting the location to the server and updating the location is %f",difference);

Both the NSlog's in the beginning of the code prints the date in the format mentioned in the date formatter correctly.

AnxiousMan
  • 578
  • 2
  • 8
  • 25
  • Update your question with the actual log output. You also need to log `timeofUpdatingLocation` and `timeofPostingToTheServer` (which I'm guessing are both `nil`). – rmaddy Jul 15 '16 at 15:00
  • And what does the `toLocalTime` method have to do with the problem? – rmaddy Jul 15 '16 at 15:00
  • My guess is that your `dateFromString` is failing for both of the dates, thereby making both dates identical and thus having 0 time between them. – Putz1103 Jul 15 '16 at 15:33

1 Answers1

2

In Objective-C it's perfectly legal to send messages to nil objects. You get back 0/nil/FALSE.

NSdateFormatter objects return nil from a call to dateFromString if the string does not match the format.

My guess is that your call to dateFromString is failing and timeofPostingToTheServer is nil, so you're getting back a 0.

(And as a footnote, as rmaddy suggests in his comment, toLocalTime does not seem to make sense with the problem you're trying to solve)

Duncan C
  • 128,072
  • 22
  • 173
  • 272