OscarTheGrouch
OscarTheGrouch

Reputation: 2384

Objective-C midpoint between two times

I have two NSDates formatted as "h:mm a" as time, (i.e. 6:00 AM and 8:00 PM).

I am trying to find out what time is the midpoint between those two times.

For the example above, the midpoint between 6:00 AM and 8:00 PM would be 1:00 PM.

But I do not know how to do this in objective-C for the iPhone sdk.

Any help or suggestions or code would be greatly appreciated.

Upvotes: 5

Views: 1281

Answers (2)

user94896
user94896

Reputation:

Perhaps something like the following is what you're after?

// Assuming you have two NSDate instances: start and end.
NSTimeInterval difference = [end timeIntervalSinceDate:start];
NSDate *middle = [NSDate dateWithTimeInterval:difference / 2 sinceDate:start];

See the NSDate Class Reference for more information.

Upvotes: 17

Todd Yandell
Todd Yandell

Reputation: 14696

Convert the times to a time interval, average the two numbers, then convert it back to an NSDate object.

Assuming your two times are instances of NSDate, that might look like this:

NSTimeInterval intA = [timeA timeIntervalSince1970];
NSTimeInterval intB = [timeB timeIntervalSince1970];

NSDate *avgTime = [NSDate dateWithTimeIntervalSince1970:(intA + intB) / 2.0];

Upvotes: 2

Related Questions