我想將datetime值轉換爲,我會從SQL Server 2008的回合.NET日期時間毫秒,因此它可以適應的SQL Server毫秒
SQL Server中的值截斷毫秒到3個位數,所以我已經截斷毫秒。但問題是,你可以在這裏看到:Milliseconds wrong when converting from XML to SQL Server datetime。 SQL Server也有一個精確問題。
我想將datetime值轉換爲,我會從SQL Server 2008的回合.NET日期時間毫秒,因此它可以適應的SQL Server毫秒
SQL Server中的值截斷毫秒到3個位數,所以我已經截斷毫秒。但問題是,你可以在這裏看到:Milliseconds wrong when converting from XML to SQL Server datetime。 SQL Server也有一個精確問題。
此代碼應工作:
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);
有點遲到了,但這裏的基於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
數據類型。
這裏有你想要的東西:
using System.Data.SqlTypes; // from System.Data.dll
public static DateTime RoundToSqlDateTime(DateTime date)
{
return new SqlDateTime(date).Value;
}
,因爲在那個「日期」參數提供的時區信息的丟失這種方式導致使用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);
}
這難道不是一樣的「新SQLDATETIME(myDateTime).value的」? – 2011-03-15 22:31:11
@Simon,是的,它似乎是一樣的! :) – 2012-08-11 19:04:40
+1僅僅是因爲代碼有助於與其他編程語言的互操作性。 ;) – 2012-09-16 17:44:22