【问题标题】:Objective-C midpoint between two times两次之间的Objective-C中点
【发布时间】:2011-07-28 03:02:36
【问题描述】:
我有两个格式为“h:mm a”作为时间的 NSDate(即 6:00 AM 和 8:00 PM)。
我试图找出这两个时间之间的中点时间。
对于上面的示例,上午 6:00 和晚上 8:00 之间的中点是下午 1:00。
但我不知道如何在 iPhone sdk 的 Objective-C 中做到这一点。
任何帮助或建议或代码将不胜感激。
【问题讨论】:
标签:
iphone
objective-c
ios4
nsdate
nscalendar
【解决方案1】:
也许你想要的是下面的东西?
// Assuming you have two NSDate instances: start and end.
NSTimeInterval difference = [end timeIntervalSinceDate:start];
NSDate *middle = [NSDate dateWithTimeInterval:difference / 2 sinceDate:start];
请参阅NSDate Class Reference 了解更多信息。
【解决方案2】:
将时间转换为时间间隔,取两个数字的平均值,然后将其转换回 NSDate 对象。
假设您的两次是 NSDate 的实例,可能如下所示:
NSTimeInterval intA = [timeA timeIntervalSince1970];
NSTimeInterval intB = [timeB timeIntervalSince1970];
NSDate *avgTime = [NSDate dateWithTimeIntervalSince1970:(intA + intB) / 2.0];