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];
}
}
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With