Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

iphone - NSDate finding nearest date to today

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?

I need to get the index of the date closest so that I can scroll to that date in my tableview.

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.

UPDATE:

I am trying this:

    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];
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...