NSDate找到最接近今天的日期 [英] NSDate finding nearest date to today
问题描述
我有一个排序的NSDates数组。有人可以帮助我找到最接近当前日期的数组中的日期吗?
I have a sorted array of NSDates. Can someone help with how I can find the date in the array that is closest to the current date?
我需要得到最接近日期的索引以便我可以滚动到我的tableview中的那个日期。
I need to get the index of the date closest so that I can scroll to that date in my tableview.
例如,如果我有2013年1月1日,2013年1月6日,2013年1月9日和2013年1月10日。我想要索引2013年1月6日。
For example, if I have Jan 1 2013, Jan 6 2013, Jan 9 2013 and Jan 10 2013. I want the index of Jan 6 2013.
希望这是有道理的。感谢您的帮助。
Hope that makes sense. Thanks for the help.
更新:
我正在尝试这样做:
NSTimeInterval interval = 0;
NSUInteger indexOfDate;
for (NSDate * date in m_arEventsSorted)
{
if(abs([date timeIntervalSinceDate:[NSDate date]]) < interval)
{
interval = abs([date timeIntervalSinceDate:[NSDate date]]);
indexOfDate = [m_arEventsSorted indexOfObject:date];
}
}
推荐答案
NSDate
提供 timeIntervalSinceNow
( reference )方法,返回 NSTimeInterval
(a typedef
'd double
)。只需在此处使用 fabs()
函数即可找到每个日期与现在之间的最小差异。
NSDate
provides the timeIntervalSinceNow
(reference) method which returns a NSTimeInterval
(a typedef
'd double
). Simply use the fabs()
function on this to find the smallest difference between each date and now.
这篇关于NSDate找到最接近今天的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!