In my integration tests I am trying to compare a C# DateTime that was inserted into a column that is defined as datetime2(0)
so obviously it loses precision on the way back out from the DB.
So my question is how do I round a C# DateTime
to datetime2(0)
precision?
I'd like to be able to go
Assert.AreEqual(insert.CreatedDateTimeUtc.RoundDateTime2(0), result.CreatedDateTimeUtc)
declare @datetime2 datetime2(0);
set @datetime2 = '2014-04-08 10:27:36.000';
print @datetime2
set @datetime2 = '2014-04-08 10:27:36.499';
print @datetime2
set @datetime2 = '2014-04-08 10:27:36.500';
print @datetime2
set @datetime2 = '2014-04-08 10:27:36.999';
print @datetime2
-- Prints
2014-04-08 10:27:36
2014-04-08 10:27:36
2014-04-08 10:27:37
2014-04-08 10:27:37
Edited to perform rounding...
So:
long tickOfSecond = original.Ticks % TimeSpan.TicksPerSecond;
long ticksToAdd = tickOfSecond < TimeSpan.TicksPerSecond / 2
? -tickOfSecond : 10000000 - tickOfSecond
DateTime truncated = original.PlusTicks(ticksToAdd);
See more on this question at Stackoverflow