I have two NSDates formatted as "h:mm a" as time, (i.e. 6:00 AM and 8:00 PM).
我有两个NSDate格式为“h:mm a”作为时间(即上午6:00和下午8:00)。
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.
对于上面的示例,上午6:00到晚上8:00之间的中点是下午1:00。
But I do not know how to do this in objective-C for the iPhone sdk.
但我不知道如何在Objective-C中为iPhone sdk做到这一点。
Any help or suggestions or code would be greatly appreciated.
任何帮助或建议或代码将不胜感激。
2 个解决方案
#1
17
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.
有关更多信息,请参阅NSDate类参考。
#2
2
Convert the times to a time interval, average the two numbers, then convert it back to an NSDate object.
将时间转换为时间间隔,将两个数字平均,然后将其转换回NSDate对象。
Assuming your two times are instances of NSDate, that might look like this:
假设你的两次是NSDate的实例,那可能是这样的:
NSTimeInterval intA = [timeA timeIntervalSince1970];
NSTimeInterval intB = [timeB timeIntervalSince1970];
NSDate *avgTime = [NSDate dateWithTimeIntervalSince1970:(intA + intB) / 2.0];
#1
17
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.
有关更多信息,请参阅NSDate类参考。
#2
2
Convert the times to a time interval, average the two numbers, then convert it back to an NSDate object.
将时间转换为时间间隔,将两个数字平均,然后将其转换回NSDate对象。
Assuming your two times are instances of NSDate, that might look like this:
假设你的两次是NSDate的实例,那可能是这样的:
NSTimeInterval intA = [timeA timeIntervalSince1970];
NSTimeInterval intB = [timeB timeIntervalSince1970];
NSDate *avgTime = [NSDate dateWithTimeIntervalSince1970:(intA + intB) / 2.0];