-1

Please tell me how can I calculate the sum of time intervals return from google's distance matrix api - for e.g. I am getting 2 days 15 hours or 5 hours 49 mins or 41 mins formate. So how can I sum up all the time intervals. Please see my response -

{
  "status": "OK",
  "origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
  "destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
  "rows": [ {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 340110,
        "text": "3 jours 22 heures"
      },
      "distance": {
        "value": 1734542,
        "text": "1 735 km"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 24487,
        "text": "6 heures 48 minutes"
      },
      "distance": {
        "value": 129324,
        "text": "129 km"
      }
    } ]
  }, {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 288834,
        "text": "3 jours 8 heures"
      },
      "distance": {
        "value": 1489604,
        "text": "1 490 km"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 14388,
        "text": "4 heures 0 minutes"
      },
      "distance": {
        "value": 135822,
        "text": "136 km"
      }
    } ]
  } ]
}
Duncan C
  • 128,072
  • 22
  • 173
  • 272
Harshit
  • 3
  • 2
  • 1
    Convert to a common unit and perform addition. `NSTimeInterval` is particularly suited for this task. – Avi Apr 18 '16 at 10:29
  • Look in the Xcode docs under "calendrical calculations". There are quite a few methods to help you with this. – Duncan C Apr 18 '16 at 10:35

3 Answers3

3

From the data you posted it looks like the server provides the time differences in both text format and as a count of seconds:

    "value": 24487,
    "text": "6 heures 48 minutes"

(6 hours 48 minutes is 24480 seconds.)

Dealing with the interval in seconds will be MUCH easier than trying to convert time interval strings back to numeric time intervals. Simply fetch the value of the "value" key and add those values together. (Those values appear to be the number of seconds that matches the string time interval.)

You can then use NSDateComponentsFormatter to convert the time interval back to a display string.

You could also use NSDateComponentsFormatter to convert your time interval strings to numeric time intervals, but you'd need to make sure you get the locale correct, and then you'd have to deal with differences between your server's string formatting and iOS's.

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

Here you can also use the simple function to get the time calculation from Google distance Matrix API.

You can also tweak this method as per requirement.

- (NSString *)getTotalTimeFromGoogleDistanceAPI:(NSArray *)timeArray
{
    double days  = 0;
    double hours = 0;
    double mins  = 0;

    for (NSString *str in timeArray) {

        // Split string into array to get values at index
        NSArray *stringSplitterArray = [str componentsSeparatedByString:@" "];

        if ([str containsString:@"day"] && [str containsString:@"hour"]) {

            days  += [[stringSplitterArray objectAtIndex:0] integerValue];
            hours += [[stringSplitterArray objectAtIndex:2] integerValue];

        }else
            if ([str containsString:@"hour"] && [str containsString:@"min"])
            {
                hours += [[stringSplitterArray objectAtIndex:0] integerValue];
                mins  += [[stringSplitterArray objectAtIndex:2] integerValue];
            }
            else
                {
                    mins  += [[stringSplitterArray objectAtIndex:0] integerValue];
                }
    }

    // Check for hours -->> if its is greater than 24 then convert it into Day
    if (hours > 23) {
        double extractDay   =  floor(hours/24);
        days += extractDay;

        double extractHours = fmod(hours, 24);
        hours = extractHours;
    }

    // Check for mins -->> if its is greater than 60 then convert it into Hours
    if (mins > 59) {
        double extractHours   =  floor(mins/60);
        hours += extractHours;

        double extractMins = fmod(mins, 60);
        mins = extractMins;
    }

    // Calculate final time
    NSString *timeString;

    if (days == 0) {
        timeString = [NSString stringWithFormat:@"%g hours %g mins", hours , mins];
    }else
        if (days == 0 && hours == 0){
            timeString = [NSString stringWithFormat:@"%g mins", mins];
        }else
            {
                timeString = [NSString stringWithFormat:@"%g days %g hours %g mins", days, round(hours) , round(mins)];
            }

    return timeString;
}

Hope this helps you.!!

Jemythehigh
  • 583
  • 5
  • 12
-2

Create a property named previousTime.

@property (nonatomic, strong) NSDate *previousTime;

Use this method to find the time difference.

 - (NSTimeInterval)timeDifferenceSinceLastOpen 
 {
    if (!previousTime) self.previousTime = [NSDate date];
    NSDate *currentTime = [NSDate date];
    NSTimeInterval timeDifference =  [currentTime timeIntervalSinceDate:prevTime];
    self.prevTime = currentTime;
    return timeDifference;
}

And do sum up. I hope, it will help you.

itsji10dra
  • 4,603
  • 3
  • 39
  • 59
Anuj J
  • 186
  • 1
  • 11