Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...