简体   繁体   中英

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

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.

Eg A sample in C# what exactly i want.

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

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

You need to parse the string into a DateTime then compare the two.

VB.NET

Dim parsed As DateTime = DateTime.Parse(hdnsdate)

If startdt != parsed Then

Else

End If

C#:

DateTime parsed = DateTime.Parse(hdnsdate);

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

I suggest looking at the different parsing methods defined on DateTime , as you may need to use a standard or custom date and time format string to ensure the string gets parsed correctly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM