Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
        }
    }
like image 268
LilMoke Avatar asked Jan 07 '13 11:01

LilMoke


3 Answers

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.

like image 61
trojanfoe Avatar answered Oct 14 '22 17:10

trojanfoe


I would recommend the timeIntervalSinceDate: function. Something like this (code not tested!):

NSDate *currentDate = [NSDate date];
double min = [currentDate timeIntervalSinceDate:[array objectAtIndex:0]];
int minIndex = 0;
for (int i = 1; i < [array count]; ++i)
{
     double currentmin = [currentDate timeIntervalSinceDate:[array objectAtIndex:i]];
     if (currentmin < min) {
           min = currentmin;
           minIndex = i;
     }
}

You can get the closest index from minIndex.

like image 2
Roosevelt Avatar answered Oct 14 '22 16:10

Roosevelt


This should work:

NSDate *closestDate;
for( NSDate *tempDate in dates ){
    NSInteger tempDateInterval = [tempDate timeIntervalSinceNow];
    //to work with positive and negative time difference
    if( tempDateInterval < 0 ){
        tempDateInterval *= -1;
    }
    NSInteger closestDateInterval = [closestDate timeIntervalSinceNow];
    if( closestDateInterval < 0 ){
        closestDateInterval *= -1;
    }
    if( tempDateInterval < closestDateInterval ){
        closestDate = tempDate;
    }
}
like image 1
Roland Keesom Avatar answered Oct 14 '22 17:10

Roland Keesom