當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


VB.NET DateTime Compare()用法及代碼示例

Compare() 方法用於比較兩個日期對象,並返回一個整數值來指定比較的結果。

用法:

Function Compare(ByVal date1 as Date, ByVal date2 as Date) as Integer

參數:

  • Date1:第一個指定的日期對象。
  • Date2:第二個指定的日期對象。

返回值:它返回一個整數值,

  • 0: 兩個日期相等。
  • 1: 第一個日期早於第二個日期。
  • -1: 第二個日期早於第一個日期。

程序/源代碼:

下麵給出了演示 DateTime 類的 Compare() 方法的源代碼。給定的程序已成功編譯並執行。

'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

輸出:

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 . . .

說明:

在上麵的程序中,我們創建了一個包含 Main() 函數的模塊 Module1。 Main() 函數是程序的入口點。

在 Main() 函數中,我們創建了三個用日期值初始化的 DateTime 類對象。然後我們比較日期對象並在控製台屏幕上打印相應的消息。





相關用法


注:本文由純淨天空篩選整理自 VB.Net program to demonstrate the Compare() method of DateTime class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。