Question

I not understand where i'm wrong to getting correct difference of two dates,

-(void)updateTimeLabel{
    NSString *serverResponseTimeString = @"02-08-2014 05:26:32";
    NSString *systemDateString = @"02-08-2014 05:31:46";
    NSDate *serverTime = [self dateFromWebStringResponse:serverResponseTimeString];
    NSDate *systemDate = [self dateFromWebStringResponse:systemDateString];

    NSLog(@"serverResponseTime %@", serverResponseTimeString);
    NSLog(@"serverTime %@", serverTime);
    NSLog(@"systemDate %@", systemDate);
    NSLog(@"difference of time %d", [self differenceOfTimeInterval:systemDate toDate:serverTime]);
}

-(NSDate *)dateFromWebStringResponse:(NSString *)dateInString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"mm-dd-yyyy hh:mm:ss"];
    NSDate *theDate = [dateFormatter dateFromString:dateInString];
    return theDate;
}


-(NSInteger)differenceOfTimeInterval:(NSDate *)fromDate toDate:(NSDate *)toDate{
    NSTimeInterval differenceOfIntervals = [toDate timeIntervalSinceDate: fromDate];
    NSInteger minutes = floor(differenceOfIntervals/60);
    return minutes;
}

Output :-

2014-02-08 17:58:57.185 iOSPractise[16770:907] serverResponseTime 02-08-2014 05:26:32
2014-02-08 17:58:57.186 iOSPractise[16770:907] serverTime 2014-01-07 23:56:32 +0000
2014-02-08 17:58:57.187 iOSPractise[16770:907] systemDate 2014-01-07 22:00:46 +0000
2014-02-08 17:58:57.188 iOSPractise[16770:907] difference of time 115 

I expect 5 minutes difference.

Was it helpful?

Solution

Your date format is wrong. The format for months is "MM" (not "mm", which are the minutes), and the 24-hour format is "HH" ("hh" is for the 12-hour am/pm hours):

[dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];

Also, as @Flexicoder mentioned, you should specify a "locale" to be independent of the user's locale settings:

[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];

(See http://www.flexicoder.com/blog/index.php/2013/10/ios-24-hour-date-format/ or What is the best way to deal with the NSDateFormatter locale "feechur"?.)

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