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

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

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

这是你想要的:

using System.Data.SqlTypes; // from System.Data.dll public static DateTime RoundToSqlDateTime(DateTime date) { return new SqlDateTime(date).Value; } 

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

  • SQL Server 2000
  • SQL Server 2005
  • SQL Server 2008

对于任何给定的日期/时间值,这应该为您提供与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数据类型,它不能正常工作。

建议在@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); } 

这段代码应该有效:

  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);