Converting from DateTime to SqlDateTime is inaccurate
asp.net, c#
Solution
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.
Problem
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 ```