Scroll through all dates with the following:
1. Have a variable that tracks the current closest date
2. Have a variable that is the difference between the current closest date and the current date.
When you find a date with a difference less than the one you are tracking in (2), update the difference and the current nearest date
At the end, the current closest date is the closest date in the collection.
here is the code in python:
dates = [date(2010,1,2), date(2010,5,6), date(2010,3,4), date(2011, 1, 2), date(2010,10,20), date(2009,2,3)] current_date = dates[0] current_min = abs(current_date - date.today()) for d in dates: if abs(d - date.today()) < current_min: current_min = abs(d - date.today()) current_date = d
Mstodd
source share