2010-05-20 58 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); 
}