views:

122

answers:

2

I have two arrays with time values in them in this format. 00:00:00 which is minutes:seconds:miliseconds. Can someone show me any easy way of adding an subtracting these values? I know I can if I break them down but I am looking for a way to do it without of code. I can get the last values which is what I want to work with like this [myArray lastObject] I tried [[myArray1 lastObject] date] - [[myArray2 lastObject] date], buy as you know that did not work. Any help would be appreciated.

+2  A: 

You should be using NSDate, NDateComponents, and NSCalendar. Study the Date and Time Programming Guide for Cocoa, which has a whole section on doing calendar-based calculations like adding hours or subtracting days.

invalidname
+1  A: 

I'm assuming you have 3 values for each time, something like:

struct TimePoint {
  int minutes;
  int seconds;
  int milliseconds;
};

If that's right, here is some code to calculate the difference:

// input is struct TimePoint t1, t2.
NSTimeInterval time1 = 60 * t1.minutes + t1.seconds + 0.001 * t1.milliseconds;
NSTimeInterval time2 = 60 * t2.minutes + t2.seconds + 0.001 * t2.milliseconds;
NSTimeInterval timeDifference = time1 - time2;

It sounds like you've also been considering working with NSDate objects. If you want to do that - suppose you want to see how much time has passed from NSDate* date1 to NSDate* date2 -- then you could use the following method (docs):

NSTimeInterval timeDiff = [date2 timeIntervalSinceDate:date1];
// value is a double in seconds; might be negative if date2 was first
Tyler