簡體   English   中英

與MaxValue的日期比較不起作用

[英]Date comparison with MaxValue not working

我有一個名為BoughtDate的可為空的Date屬性。 我正在嘗試以下方法:

if( item.BoughtDate.Value.Equals( DateTime.MaxValue) ) item.BoughtDate= null;

還試過這個:

if( item.BoughtDate.Equals( DateTime.MaxValue) ) item.BoughtDate=null;

在調試時,我的BoughtDateDateTime.MaxValue看起來完全一樣 - 但它說它不一樣(沒有將我的item.BoughtDate設置為null)

為什么我的比較不起作用?

正如@PaulSuart在評論中指出的那樣,問題可能是毫秒精度。 DateTime.MaxValue.TimeOfDay{23:59:59.9999999} ,但你的BoughtDate.TimeOfDay可能是{23:59:59.9990000} ,所以它們不相等。

我要做的只是比較日期,我認為在大多數情況下這已足夠:

if( item.BoughtDate.Value.Date.Equals( DateTime.MaxValue.Date) ) item.BoughtDate= null;

編輯:正如有人指出它沒有回答原始問題,只是提供了另一種選擇。

嘗試使用DateTime.Compare

https://msdn.microsoft.com/pl-pl/library/system.datetime.compare(v=vs.110).aspx

public static void Main()
{
  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);
}

在你的例子中可能是這樣的:

if(DateTime.Compare(item.BoughtDate.Value,DateTime.MaxValue) == 0) item.BoughtDate=null;

我為你的案子做了快速測試:

static void Main(string[] args)
{
    DateTime? BoughtDate = DateTime.MaxValue;
    //subtract 100 milliseconds from it
    BoughtDate = BoughtDate.Value.AddMilliseconds(-1);

    Console.WriteLine(BoughtDate.Value.Hour); //23
    Console.WriteLine(DateTime.MaxValue.Hour); //23

    Console.WriteLine(BoughtDate.Value.Minute); //59
    Console.WriteLine(DateTime.MaxValue.Minute); //59

    Console.WriteLine(BoughtDate.Value.Second); //59
    Console.WriteLine(DateTime.MaxValue.Second); //59

    Console.WriteLine(BoughtDate.Value.Year); //9999
    Console.WriteLine(DateTime.MaxValue.Year); //9999

    Console.WriteLine(BoughtDate.Value.Month); //12
    Console.WriteLine(DateTime.MaxValue.Month); //12

    Console.WriteLine(BoughtDate.Value.Day); //31
    Console.WriteLine(DateTime.MaxValue.Day); //31

    Console.WriteLine(BoughtDate.Value.Millisecond); //998
    Console.WriteLine(DateTime.MaxValue.Millisecond); //999



    if (BoughtDate.Value.Equals(DateTime.MaxValue)) 
    {
        Console.WriteLine("equals comparison succeeded"); //doesn't get printed
    }
}

在從原始值減少一毫秒后,它不會在if塊中通過相等檢查條件,但如果您在快速監視窗口中看到BoughtDate的值, 它們看起來與您所說的完全相同 (因為它僅顯示年,月,日) ,小時,分鍾和秒鍾)。

在此輸入圖像描述

只有在展開+號時才會顯示毫秒部分。

因此,您的日期時間變量必須以毫秒為單位,即使它們看起來一目了然。

如果您從SQL-Server獲取日期,我想您可能會在下面的鏈接中找到答案。 SQL-Server僅支持23:59:59.997之間的時間范圍,這可能導致幾個小於C#支持的小節。 你可以比較@Pikoh已經提到過的日期。

https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM