我想将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