什么是比较两个日期时间在C#中的平等的最好方式......但只有在一定的精度? [英] What's the best way to compare the equality of two DateTime's in C#... but only to a certain precision?
问题描述
我有两个日期时间,一名来自时间戳,另一个我在代码中产生。我需要测试他们的平等,并会喜欢做没有太多的表情。这里是我的两个日期的例子:
I have two datetimes, one from a timestamp, and another I'm generating in code. I need to test their equality, and would love to do it without too many expressions. Here's an example of my two dates:
DateTime expireTimeStampUTC =
DateTime.Parse(UTCValueFromDatabase));
DateTime expectedExpireTime =
DateTime.UtcNow.AddHours(NumberOfExpectedHoursInConfig);
这是一个测试过高精度:
This is too high precision of a test:
如果(expireTimeStampUTC.Equals(expectedExpireTime)){}
if (expireTimeStampUTC.Equals(expectedExpireTime)){}
我如果他们精确到秒,就在小时无所谓了。
I don't care if they're exact to the second, just the hour.
难道可能会做这样的事情化合物最好的解决办法:
Could it possibly be the best solution to do something compound like this:
if (expireTimeStampUTC.Date.Equals(expectedExpireTime.Date))
{
if (!expireTimeStampUTC.Hour.Equals(expectedExpireTime.Hour))
{
pass = false;
}
}
我不是最有经验与C#.. 。有一些高贵的方式来做到这一点?
I'm not the most experienced with C#... is there some elegent way to do this?
推荐答案
如果您遇到的问题是,因为他们是一个数据库类型,你可以转换成该类型和比较那里,我们失去了约一毫秒转换为SQLDateTimes上大致DB的1/3节省/增益。
If the problem you are having is because of them is a database type, you could convert to that type and compare there, we lose/gain about a millisecond converting to SQLDateTimes on roughly 1/3 of DB saves.
如果没有,比较单元你真正关心的:
If not, compare the unit you actually care about:
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
或者如果你关心自己是一个小时的时间跨度内
or if you care that they are within an hour time span
// 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)单位明确创建的限制和比较。
Here subtracting dates generates a time span, the duration is the 'absolute value' and then we create the limit explicitly from a unit we care about (FromHours) and compare.
最后一行是我能想到做一个特定的时间范围内平等干净。
The last line is as clean as I can think to do equality within a particular time span.
这篇关于什么是比较两个日期时间在C#中的平等的最好方式......但只有在一定的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!