2010-05-20 30 views

回答

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

有点迟到了,但这里的基于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

这难道不是一样的“新SQLDATETIME(myDateTime).value的”? – 2011-03-15 22:31:11

+0

@Simon,是的,它似乎是一样的! :) – 2012-08-11 19:04:40

+1

+1仅仅是因为代码有助于与其他编程语言的互操作性。 ;) – 2012-09-16 17:44:22

21

这里有你想要的东西:

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

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

,因为在那个“日期”参数提供的时区信息的丢失这种方式导致使用SQLDATETIME的建议构建在@RobSiklos解决方案。找到它的最佳实践,以确保时区信息是在转换点一致通过向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); 
}