Flex : Find Closest Date for a given Date

On October 12, 2010, in Flex, by Anuj Gakhar

This requirement came up today at work where I had an ArrayCollection of Date Objects and then I had another Date Object and I wanted to find from my Collection of Dates, the closest Date to my given Date – whether in the past or the future. Although this does not sound like a very complex scenario – I do not think this is a very common scenario as well. Hence, this blog post.

First of all, I had to figure out the logic behind this. I understand there can be several ways of doing this, but the way I came up was to create a temporary ArrayCollection, calculate the difference in Days of each Date in my Collection with the target Date and populate the temp collection. Make sure to get the Absolute values since we are not bothered whether the date is in past or future. And then Sort the Temp Collection by this absolute value. The first element would be my closest Date.

I decided to write up a sample application to demonstrate this. You can generate Random dates and then select a target date and then find the Closest Date to that date. If everything works fine, the List will scroll to the selected Index as well. View source is enabled in the application, feel free to have a look.

[SWF]/wp-content/datedemo/DateSort.swf, 390, 350[/SWF]

Tagged with:  

4 Responses to Flex : Find Closest Date for a given Date

  1. senling says:

    Nice stuff. keep it up

  2. oxido says:

    Can you give us the source file,please?

  3. oxido says:

    ohh… thx man, I did not know that such a thing can be done.

    You’re a gold mine!

Leave a Reply to oxido Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: