Find nearest date among several dates to a given date

前端 未结 5 1434
一个人的身影
一个人的身影 2020-12-10 14:58

I have a list of dates and a current date. How can I find the date which is nearest to the current date?

5条回答
  •  天涯浪人
    2020-12-10 15:15

    Loop through all dates with the following:
    1. Have a variable that keeps track of 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 that of the what you're keeping track of in (2), update the difference and the current closest date

    At the end, the current closest date is the closest date in the collection

    here's 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
    

提交回复
热议问题