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

时间:2010-05-20 09:25:55

标签: c# sql-server sql-server-2008 datetime

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

SQL Server将毫秒截断为3位数,因此我已经截断了毫秒数。但问题是,你可以在这里看到:Milliseconds wrong when converting from XML to SQL Server datetime。 SQL Server也存在精度问题。

4 个答案:

答案 0 :(得分:21)

这是你想要的:

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

public static DateTime RoundToSqlDateTime(DateTime date)
{
  return new SqlDateTime(date).Value;
}

答案 1 :(得分:10)

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

对于任何给定的日期/时间值,这应该为您提供与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 ;
    }
}

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

答案 2 :(得分:4)

建议在@RobSiklos解决方案的基础上进行构建,因为以这种方式使用SqlDateTime会导致时区信息的丢失,而这些信息会在&#39; date&#39;论证提供。找到最佳实践,通过添加对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);
}

答案 3 :(得分:3)

此代码应该有效:

        int ticksInMillisecond = 10000;
        DateTime t1 = DateTime.Now;
        DateTime t2 = new DateTime(t1.Ticks / ticksInMillisecond * ticksInMillisecond);

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

        int precisionTicks = 100000;
        DateTime t1 = DateTime.Now;
        DateTime t2 = new DateTime(t1.Ticks / precisionTicks * precisionTicks);
相关问题