DateTime.Compare(DateTime, DateTime) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
比較 DateTime 的兩個執行個體,並傳回整數,這個整數表示第一個執行個體早於、同於或晚於第二個執行個體。
public:
static int Compare(DateTime t1, DateTime t2);
public static int Compare (DateTime t1, DateTime t2);
static member Compare : DateTime * DateTime -> int
Public Shared Function Compare (t1 As DateTime, t2 As DateTime) As Integer
參數
- t1
- DateTime
要比較的第一個物件。
- t2
- DateTime
要比較的第二個物件。
傳回
帶正負號的數字,該數字表示 t1
和 t2
的相對值。
實值類型 | 條件 |
---|---|
小於零 |
t1 早於 t2 。
|
零 |
t1 與 t2 相同。
|
大於零 |
t1 晚於 t2 。
|
範例
下列範例示範 Compare 方法。
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
// The example displays the following output for en-us culture:
// 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
let date1 = DateTime(2009, 8, 1, 0, 0, 0)
let date2 = DateTime(2009, 8, 1, 12, 0, 0)
let result = DateTime.Compare(date1, date2)
let relationship =
if result < 0 then
"is earlier than"
elif result = 0 then
"is the same time as"
else
"is later than"
printfn $"{date1} {relationship} {date2}"
// The example displays the following output for en-us culture:
// 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
Module Example
Public Sub Main()
Dim date1 As Date = #08/01/2009 12:00AM#
Dim date2 As Date = #08/01/2009 12:00PM#
Dim result As Integer = DateTime.Compare(date1, date2)
Dim relationship As String
If result < 0 Then
relationship = "is earlier than"
ElseIf result = 0 Then
relationship = "is the same time as"
Else
relationship = "is later than"
End If
Console.WriteLine("{0} {1} {2}", date1, relationship, date2)
End Sub
End Module
' The example displays the following output:
' 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
備註
若要判斷 與 的 t1
t2
關聯性, Compare 方法會 Ticks 比較 和 t2
的 t1
屬性,但會忽略其 Kind 屬性。 比較 DateTime 物件之前,請確定物件代表相同時區中的時間。