簡體   English   中英

在 C# 中比較兩個 DateTime 的相等性的最佳方法是什么……但只能達到一定的精度?

[英]What's the best way to compare the equality of two DateTime's in C#… but only to a certain precision?

我有兩個日期時間,一個來自時間戳,另一個是我在代碼中生成的。 我需要測試它們的平等性,並且願意在沒有太多表達的情況下做到這一點。 這是我的兩個日期的示例:

DateTime expireTimeStampUTC = 
    DateTime.Parse(UTCValueFromDatabase));
DateTime expectedExpireTime = 
    DateTime.UtcNow.AddHours(NumberOfExpectedHoursInConfig);

這是一個測試的精度太高:

if (expireTimeStampUTC.Equals(expectedExpireTime)){}

我不在乎它們是否精確到秒,只是小時。

它可能是做這樣的復合的最佳解決方案:

if (expireTimeStampUTC.Date.Equals(expectedExpireTime.Date))
{
    if (!expireTimeStampUTC.Hour.Equals(expectedExpireTime.Hour))
    {
        pass = false;
    }
}

我對 C# 不是最有經驗的......有什么優雅的方法可以做到這一點嗎?

如果您遇到的問題是因為它們是數據庫類型,您可以轉換為該類型並在那里進行比較,我們在大約 1/3 的數據庫保存中損失/獲得大約一毫秒轉換為 SQLDateTimes。

如果不是,請比較您真正關心的單位:

DateTime dt1 = DateTime.UtcNow;
DateTime dt2 = DateTime.UtcNow.AddMinutes(59); // or 1 or 61 for test values;

// if the dates are in the same hour (12:10 == 12:50, 1:58 != 2:02)
if(dt1.Hour == dt2.Hour) // result

或者如果你關心他們在一小時的時間跨度內

// if the dates are within one hour of each other (1:58 == 2:02, 3:30 != 4:45)
if((dt1 - dt2).Duration() < TimeSpan.FromHours(1)) // result

這里減去日期會生成一個時間跨度,持續時間是“絕對值”,然后我們從我們關心的單位(FromHours)顯式創建限制並進行比較。

最后一行是我認為在特定時間跨度內進行平等的干凈利落。

如何找出兩個小時之間的差異,看看它是否低於某個閾值(比如一個小時 3600 秒)?

var diff = expireTimeStamp.Subtract(expectedExpireTime).TotalSeconds;
pass = Math.Abs(diff) < 3600;

減去它們。 檢查生成的TimeSpan是否在某個最大范圍內。

構造新的 DateTime 對象並比較它們。 在 C# 中,以這種方式構造“一次性”對象的懲罰很少。

我在嘗試編寫提交然后檢索業務對象的單元測試時遇到了這個問題。 我試圖使用 object 的“StartTime”屬性來確保可以檢索 object 並遇到此問題。 數據庫中提交的“StartTime”值在 Ticks 值中丟失了 6 位精度!

這是我重寫測試條件的方法,以便我的測試能夠正確執行並通過。 相關行是塊的倒數第二行。

DateTime start = DateTime.Now;
NewEventInfo testEvent1 = FakeEvent("test01action", start); //plus other params for testing
mServiceClient.AddEvent(testEvent1);

EventInfo[] eventInfos = null; //code to get back events within time window

Assert.IsNotEmpty(eventInfos);
Assert.GreaterOrEqual(eventInfos.Length, 1);

EventInfo resultEvent1 = eventInfos.FirstOrDefault(e => 
e.Action == "test01action" &&
Math.Abs(e.StartTime.Subtract(testEvent1.StartTime).TotalMilliseconds) < 1000); //checks dates are within 1 sec
Assert.IsNotNull(resultEvent1);

這樣我可以確定 object 是單元測試提交的,因為 EventInfo.StartTime 屬性僅使用精度為 1 秒的日期時間。

編輯:添加了 Math.Abs(圍繞 DateTime diff)以確保將絕對值與 1000 進行比較。

暫無
暫無

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

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