Compare two dates in vb.net whether they are equal or not

Ishan picture Ishan · Dec 28, 2011 · Viewed 22.7k times · Source

I have a Date variable startdt and a String variable hdnsdate.

Suppose if startdt has the value in the form 3/1/2012 and hdnsdate has the value in the form 03/01/2012. Than how can i compare that these two dates are equal in vb.net.

In if condition of my program i want to do this check. In case the two dates match move out of if loop otherwise go into the if loop.

E.g A sample in C# what exactly i want.

if(startdt !=hdnsdate)
{
 //Do
}
else
{
//Do this
}

Answer

kv-prajapati picture kv-prajapati · Dec 28, 2011

Parse hdnsdate (string) to Date type using Parse, ParseExact method and use DateTime.Compare, Equals, CompareTo methods.

String to date

 Dim enddate as Date
 Date.TryParse(hdnsdate, enddate)

 If startdt = enddate Then
   'Do this
 Else
   'Do this
 End If

Alternative to compare date:

Dim result = DateTime.Compare(date1, date2)
If result=0 Then
  'Do this
End If