Find date closest to todays date from list

How can I find the closest date to todays date from a combo box with multiple varying dates in?
Terry RogersIT Senior EngineerAsked:
Who is Participating?
Mortaza DoulatyConnect With a Mentor Commented:
Here is the code snippet:

        Dim closetDayIndex As Integer = -1
        Dim daysCount As Integer = System.Int32.MaxValue
        Dim dtc As New DateTimeConverter
        Dim dt As DateTime

        For index = 0 To Me.ComboBox1.Items.Count - 1
            dt = dtc.ConvertFromString(Me.ComboBox1.Items(index))
            If ((DateTime.Now - dt).TotalDays < daysCount) Then
                daysCount = (DateTime.Now - dt).TotalDays
                closetDayIndex = index
            End If

        MessageBox.Show("Closet day: " + Me.ComboBox1.Items(closetDayIndex))

Open in new window

Mortaza DoulatyCommented:
You can calculate the difference of each date in combo box with today's date, then sort the list ascending and get the closet date.

If you need, please let me know to post a code snippet.
Terry RogersIT Senior EngineerAuthor Commented:
A code snippet will be helpfull as am still new to VB.NET programming! :)
7 new features that'll make your work life better

It’s our mission to create a product that solves the huge challenges you face at work every day. In case you missed it, here are 7 delightful things we've added recently to monday to make it even more awesome.

// Store current datetime in a variable
DateTime currentDateTime = DateTime.Now;
// Declare variable to store combobox date
DateTime ComboDateTime;
DateTime closestDateTime;

int prevDiff;
int currentDiff;
int i;
TimeSpan span;
prevDiff = 0;
//Loop thru combo box items
for (i = 0; i <= ComBoBox.Items.Count -1
; i++) {
// Populate the variable to combo box date
ComboDateTime = ComboBox.Items(i)
currentDiff = ComboDateTime.Subtract ( currentDateTime );
if (currentDiff < prevDiff)
{   closestDateTime = ComboDateTime.Items(i);
   prevDiff = currentDiff;
// variable closestDateTime has the closest date now
Mortaza DoulatyCommented:
Also note that DateTimeConverter is in 'System.ComponentModel' namespace, so do not remember to include that namespace.
Please replace the following line
currentDiff = ComboDateTime.Subtract ( currentDateTime );

in my previous post with the following

span = ComboDateTime.Subtract ( currentDateTime );
currentDiff = span.Seconds;
if (currentDiff < prevDiff)
Mortaza DoulatyCommented:
AmitGK, please note that Terry is using VB .NET, not C#...
Terry RogersIT Senior EngineerAuthor Commented:
Thanks! :)
Mortaza_doulaty, fine noted man ;).
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.