如何将C#datetime舍入到datetime2(0)

时间:2014-04-08 21:45:30

标签: c# sql-server

在我的集成测试中,我试图比较插入到定义为datetime2(0)的列中的C#DateTime,因此显然它在从DB退出的路上失去了精度。

所以我的问题是如何将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

3 个答案:

答案 0 :(得分:3)

编辑执行舍入......

所以:

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

答案 1 :(得分:3)

您可以使用NUnits EqualConstraint:

  

可以使用或不使用a来比较DateTimes和TimeSpans   公差。使用WITH指定公差   TimeSpan作为参数或数值后跟一个   时间转换修饰符:天,小时,分钟,秒,   毫秒或滴答。

http://www.nunit.org/index.php?p=equalConstraint&r=2.5.5

[TestFixture]
public class DateTime2Tests
{
    [Test]
    public void TestRoundDateTime2_RoundsDown_000()
    {
        var date = new DateTime(2014, 12, 31, 10, 27, 36, 000);
        var xxxx = new DateTime(2014, 12, 31, 10, 27, 36);
        Assert.That(xxxx, Is.EqualTo(date).Within(TimeSpan.FromSeconds(1)));
    }

    [Test]
    public void TestRoundDateTime2_RoundsDown_499()
    {
        var date = new DateTime(2014, 12, 31, 10, 27, 36, 499);
        var xxxx = new DateTime(2014, 12, 31, 10, 27, 36);
        Assert.That(xxxx, Is.EqualTo(date).Within(TimeSpan.FromSeconds(1)));
    }

    [Test]
    public void TestRoundDateTime2_RoundsUp_500()
    {
        var date = new DateTime(2014, 12, 31, 10, 27, 36, 500);
        var xxxx = new DateTime(2014, 12, 31, 10, 27, 37);
        Assert.That(xxxx, Is.EqualTo(date).Within(TimeSpan.FromSeconds(1)));
    }

    [Test]
    public void TestRoundDateTime2_RoundsUp_750()
    {
        var date = new DateTime(2014, 12, 31, 10, 27, 36, 750);
        var xxxx = new DateTime(2014, 12, 31, 10, 27, 37);
        Assert.That(xxxx, Is.EqualTo(date).Within(TimeSpan.FromSeconds(1)));
    }

    [Test]
    public void TestRoundDateTime2_RoundsUp999()
    {
        var date = new DateTime(2014, 12, 31, 10, 27, 36, 999);
        var xxxx = new DateTime(2014, 12, 31, 10, 27, 37);
        Assert.That(xxxx, Is.EqualTo(date).Within(TimeSpan.FromSeconds(1)));
    }
}

答案 2 :(得分:0)

datetime2(0)定义了一个没有小数秒的日期时间,例如毫秒始终等于0.毫秒内有10,000个刻度。

var rounded = new DateTime(
    original.Ticks - (original.Millisecond * TimeSpan.TicksPerMillisecond)
);