在我的集成测试中,我试图比较插入到定义为datetime2(0)的列中的C#DateTime,因此很显然,它在从数据库中退出时会失去精度。

所以我的问题是如何将C#DateTime舍入为datetime2(0)精度?

我想去
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

最佳答案

编辑以执行舍入...

所以:

long tickOfSecond = original.Ticks % TimeSpan.TicksPerSecond;
long ticksToAdd = tickOfSecond < TimeSpan.TicksPerSecond / 2
         ? -tickOfSecond : 10000000 - tickOfSecond
DateTime truncated = original.PlusTicks(ticksToAdd);

关于c# - 如何将C#日期时间四舍五入为datetime2(0),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22948825/

10-12 21:46