Round .NET DateTime毫秒,因此它可以适合SQL Server毫秒

sta*_*ker 15 c# sql-server datetime sql-server-2008

我想将datetime值转换为我将从SQL Server 2008获得的值.

SQL Server将毫秒截断为3位数,因此我已经截断了毫秒数.但问题是,正如您在此处看到的:从XML转换为SQL Server datetime时,毫秒错误.SQL Server也存在精度问题.

Rob*_*los 21

这是你想要的:

using System.Data.SqlTypes; // from System.Data.dll

public static DateTime RoundToSqlDateTime(DateTime date)
{
  return new SqlDateTime(date).Value;
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*rey 11

派对有点晚了,但这里有一个解决方案,基于datetime不同版本SQL Server 的数据类型的SQL Server文档:

对于任何给定的日期/时间值,这应该为您提供与SQL Server完全相同的值:

public static class DateTimeExtensions
{
                                   //  milliseconds modulo 10:    0    1    2    3    4    5    6    7    8    9
    private static readonly int[]    OFFSET                  = {  0 , -1 , +1 ,  0 , -1 , +2 , +1 ,  0 , -1 , +1 } ;
    private static readonly DateTime SQL_SERVER_DATETIME_MIN = new DateTime( 1753 , 01 , 01 , 00 , 00 , 00 , 000 ) ;
    private static readonly DateTime SQL_SERVER_DATETIME_MAX = new DateTime( 9999 , 12 , 31 , 23 , 59 , 59 , 997 ) ;

    public static DateTime RoundToSqlServerDateTime( this DateTime value )
    {
        DateTime dt           = new DateTime( value.Year , value.Month , value.Day , value.Hour , value.Minute , value.Second , value.Millisecond) ;
        int      milliseconds = value.Millisecond ;
        int      t            = milliseconds % 10 ;
        int      offset       = OFFSET[ t ] ;
        DateTime rounded      = dt.AddMilliseconds( offset ) ;

        if ( rounded < SQL_SERVER_DATETIME_MIN ) throw new ArgumentOutOfRangeException("value") ;
        if ( rounded > SQL_SERVER_DATETIME_MAX ) throw new ArgumentOutOfRangeException("value") ;

        return rounded ;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,对于smalldatetime新的datetime2数据类型,它不会正常工作.

  • 这不是'new SqlDateTime(myDateTime).Value'吗? (2认同)

Bob*_*Bob 5

推荐使用@RobSiklos解决方案,因为以这种方式使用SqlDateTime会导致丢失'date'参数提供的时区信息。通过添加对DateTime.SpecifyKind的调用,找到最佳实践,以确保时区信息在转换时保持一致。

using System.Data.SqlTypes; // from System.Data.dll

public static DateTime RoundToSqlDateTime(DateTime date)
{
  return DateTime.SpecifyKind( new SqlDateTime(date).Value, date.Kind);
}
Run Code Online (Sandbox Code Playgroud)


Reg*_*ent 3

这段代码应该可以工作:

        int ticksInMillisecond = 10000;
        DateTime t1 = DateTime.Now;
        DateTime t2 = new DateTime(t1.Ticks / ticksInMillisecond * ticksInMillisecond);
Run Code Online (Sandbox Code Playgroud)

但考虑到SQL Server的精度问题,我宁愿在秒后将其截断为两位数:

        int precisionTicks = 100000;
        DateTime t1 = DateTime.Now;
        DateTime t2 = new DateTime(t1.Ticks / precisionTicks * precisionTicks);
Run Code Online (Sandbox Code Playgroud)