What is the best way to compare the equality of two DateTimes in C # ... but only with a certain precision?

I have two times, one is a timestamp and the other is code. I need to check their equality and would like to do it without too many expressions. Here is an example of my two dates:

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

This is too high a test accuracy:

if (expireTimeStampUTC.Equals (expectedExpireTime)) {}

I don’t care if they are accurate to the second, only an hour.

Could this be a better solution to do something like this:

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

I'm not the most experienced in C # ... is there any elegant way to do this?

+6
date c # datetime
source share
5 answers

If the problem you are facing because of them is the database type, you can convert it to this type and compare there, we lose / get about a millisecond conversion to SQLDateTimes by about 1/3 of the DB.

If not, compare the block you really need:

 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 are interested in what they are in the hour

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

Here, subtracting dates generates a time interval, duration is an “absolute value”, and then we create a constraint explicitly from the unit we care about (FromHours) and compare.

The last line is as clean as I can think, to make equality for a certain period of time.

+10
source share

How to find the difference between two hours and see if it is below a certain threshold (say, 3600 seconds in an hour)?

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

Subtract them. Check if the TimeSpan is within the defined maximum range.

+4
source share

Create new DateTime objects and compare them. Thus, in C # there is very little penalty for creating “discarded” objects.

+1
source share

I ran into a problem while trying to write unit tests that fixed and then retrieved business objects. I tried to use the "StartTime" property of my object to ensure that the object can be restored and run into this problem. The "StartTime" value recorded in the database has lost 6 precision digits in the Ticks!

This is how I rewrote my test condition so that my test runs correctly and passes. The corresponding line is the second to last line of the block.

 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); 

That way, I could be sure that the object was the one that was recorded by unit test, because the EventInfo.StartTime property uses only date time with an accuracy of 1 second.

EDIT: Added Math.Abs ​​(around DateTime diff) to provide an absolute value compared to 1000.

+1
source share

All Articles