Home »
VB.Net »
VB.Net Programs
VB.Net program to demonstrate the Compare() method of DateTime class
By Nidhi Last Updated : November 11, 2024
DateTime.Compare() Method in VB.Net
The Compare() method is used to compare two date objects and return an integer value to specify the result of comparison.
Syntax
Function Compare(ByVal date1 as Date, ByVal date2 as Date) as Integer
Parameter(s)
- Date1 : First specified date object.
- Date2 : Second specified date object.
Return Value
It returns an integer value,
- 0 : Both dates are equal.
- 1 : The first date is earlier than the second date.
- -1 : The second date is earlier than the first date.
VB.Net code to demonstrate the example of DateTime.Compare() method
The source code to demonstrate the Compare() method of the DateTime class is given below. The given program is compiled and executed successfully.
'VB.NET program to demonstrate Compare() method of
'DateTime class.
Imports System
Module Module1
Sub Main()
Dim date1 As New DateTime(2020, 4, 27)
Dim date2 As New DateTime(2021, 3, 28)
Dim date3 As New DateTime(2021, 3, 28)
Dim ret As Integer = 0
ret = DateTime.Compare(date1, date2)
If (ret < 0) Then
Console.WriteLine("{0} is earlier than {1}", date1, date2)
ElseIf (ret = 0) Then
Console.WriteLine("{0} and {1} are equal", date1, date2)
Else
Console.WriteLine("{0} is earlier than {1}", date2, date1)
End If
ret = DateTime.Compare(date2, date3)
If (ret < 0) Then
Console.WriteLine("{0} is earlier than {1}", date1, date2)
ElseIf (ret = 0) Then
Console.WriteLine("{0} and {1} are equal", date1, date2)
Else
Console.WriteLine("{0} is earlier than {1}", date2, date1)
End If
End Sub
End Module
Output
27-04-2020 00:00:00 is earlier than 28-03-2021 00:00:00
27-04-2020 00:00:00 and 28-03-2021 00:00:00 are equal
Press any key to continue . . .
Explanation
In the above program, we created a module Module1 that contains the Main() function. The Main() function is the entry point for the program.
In the Main() function, we created three objects of the DateTime class that are initialized with date values. Then we compared date objects and print the appropriate message on the console screen.
VB.Net Date & Time Programs »