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

Categories

0 votes
606 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...