从日期时间转换为SQLDATETIME不准确 [英] Converting from DateTime to SqlDateTime is inaccurate
问题描述
我有一个从源获取一个日期属性的方法(无论是的DataRow
或 SqlDataReader的
):
保护SQLDATETIME GetSqlDateTimePropertyValue(字符串propertyName的,对象源)
{
VAR objValue = GetPropertyValue(propertyName的,源);
VAR值= objValue == DBNull.Value?空:(?DATETIME)objValue;
VAR sqlValue =新SQLDATETIME();
如果(value.HasValue)sqlValue = value.Value;
返回sqlValue;
}
但转换似乎稍微改变了日期,以便我的测试总是失败。
有谁知道为什么这种方法会被错误地转换?
在方法的结尾,它看起来像转化为 SQLDATETIME
做了一些四舍五入:
value.Value.Ticks:634698391707468296
sqlValue.Value.Ticks:634698391707470000
是 - 在SQL Server DATETIME
的时间分别是3.33ms的精确度 - 在.NET数据类型但可以重新present单毫秒。
因此,你将有一些问题,舍入有时。
阅读了很多关于在 DATETIME
的数据类型和它的属性和怪癖的位置:
此外,SQL Server 2008中引入新的日期相关的数据类型的转换 - 阅读更多关于那些在这里:
SQL Server 2008中新的datetime数据类型
这些类型做包括 DATETIME2
数据类型是精确到100ns的。
I have a method that gets a date property from a source (either a DataRow
or a SqlDataReader
):
protected SqlDateTime GetSqlDateTimePropertyValue(string propertyName, object source)
{
var objValue = GetPropertyValue(propertyName, source);
var value = objValue == DBNull.Value ? null : (DateTime?)objValue;
var sqlValue = new SqlDateTime();
if (value.HasValue) sqlValue = value.Value;
return sqlValue;
}
but the conversion appears to be changing the date slightly so that my test always fails.
Does anyone know why this method would be converting wrongly?
At the end of the method, it looks like the conversion to SqlDateTime
does some rounding:
value.Value.Ticks: 634698391707468296
sqlValue.Value.Ticks: 634698391707470000
Yes - the SQL Server DATETIME
has an accuracy of 3.33ms - the .NET datatype however can represent single milliseconds.
Therefore, you will have some rounding issues at times.
Read a lot more about the DATETIME
datatype and its properties and quirks here:
Demystifying the SQL Server DATETIME datatype
Also, SQL Server 2008 introduced a slew of new date-related data types - read more about those here:
SQL Server 2008 New DATETIME datatypes
These types do include a DATETIME2
datatype which is accurate to 100ns.
这篇关于从日期时间转换为SQLDATETIME不准确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!