Question

I am trying to find the time difference between 2 dates. but i am getting values as -0.0000, nan, or -357683564. below is my code to find time difference. am i doing any wrong in this calculations ?

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterNoStyle;
formatter.dateFormat = @"YYYY-MM-dd HH:MM:SS ±HHMM";//MM/dd/yyyy
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:usLocale];
NSDate *intialTime= [formatter dateFromString:[NSString stringWithFormat:@"%@",[dateArray objectAtIndex:i]]];//[formatter dateFromString:@"12/11/2005"];
NSDate *presentDate = [NSDate date];
NSTimeInterval timeInterval = [presentDate timeIntervalSinceDate:intialTime];
int seconds = (int)ceil(timeInterval);
int mins = seconds / 60;
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = timeInterval / secondsInAnHour;
NSLog(@"Time interval in Mins:%d -- %.4f -- %d",mins,timeInterval,hoursBetweenDates);

In Log :

Time interval in Mins:-35791394 -- nan -- -2147483648

intialTime - (null) and presentDate - 2014-05-09 10:30:15 +0000

Was it helpful?

Solution 2

I fixed my Issue by using NSTimeZone. here was my problem.it was displaying date as their server date and my current date was not matching to timezone and not able to format it. Thanks for you all friends for helping me to find my mistake.

    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
    [dateFormatter setTimeZone:gmt];

OTHER TIPS

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];

    NSDate *dateToday = [NSDate date];

    NSString *date = @"09-05-14";   // Put your initial date here...

    [df setDateFormat:@"HH:mm:ss"];
    NSString *todayString = [df stringFromDate:[NSDate date]];
    NSString *todaysDateTime = [date stringByAppendingString:todayString];

    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *initialDate = [df dateFromString:todaysDateTime];

    NSTimeInterval ti = [initialDate timeIntervalSinceDate:dateToday];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top