Compare two dates using DateTime in Vb.net

How to compare two dates using DateTime and VB.NET.
  • 28973

Compare Two DateTime 
 

The Compare static method is used to compare two DateTime objects. If result is 0, both objects are same. If result is less than 0, the first DateTime is earlier; otherwise the first DateTime is later. 
 

The code snippet in Listing 8 compares two DateTime objects. 
 

Dim firstDate As DateTime = New DateTime(2002, 10, 22)
        Dim secondDate As DateTime = New DateTime(2009, 8, 11)
        Dim result As Int16 = DateTime.Compare(firstDate, secondDate)

        If (result < 0) Then
            Console.WriteLine("First date is earlier")
        ElseIf (result = 0) Then
            Console.WriteLine("Both dates are same")
        Else
            Console.WriteLine("First date is later")
        End 
If

Listing 8

The CompareTo method can also be used to compare two dates. This method takes a DateTime or object. The code snippet in Listing 9 compares two DateTime objects using the CompareTo method. 
 

    Private Sub CompareTwoStrings()
        Dim compareResult As Int16 = firstDate.CompareTo(secondDate)
        If (compareResult < 0) Then
            Console.WriteLine("First date is earlier")
        ElseIf (compareResult = 0) Then
            Console.WriteLine("Both dates are same")
        Else
            Console.WriteLine("First date is later")

        End If
    End 
Sub

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.