I’ve run into a problem related to converting datetimes from XML (ISO8601: yyyy-mm-ddThh:mi:ss.mmm) to SQL Server 2005 datetime. The problem is when converting the milliseconds are wrong. I’ve tested both implicit and explicit conversion using convert(datetime, MyDate, 126) from nvarchar, and the result is the same:
Original Result 2009-10-29T15:43:12.990 2009-10-29 15:43:12.990 2009-10-29T15:43:12.991 2009-10-29 15:43:12.990 2009-10-29T15:43:12.992 2009-10-29 15:43:12.993 2009-10-29T15:43:12.993 2009-10-29 15:43:12.993 2009-10-29T15:43:12.994 2009-10-29 15:43:12.993 2009-10-29T15:43:12.995 2009-10-29 15:43:12.997 2009-10-29T15:43:12.996 2009-10-29 15:43:12.997 2009-10-29T15:43:12.997 2009-10-29 15:43:12.997 2009-10-29T15:43:12.998 2009-10-29 15:43:12.997 2009-10-29T15:43:12.999 2009-10-29 15:43:13.000
My non-extensive testing shows that the last digit is either 0, 3 or 7. Is this a simple rounding problem? Millisecond precision is important, and losing/gaining one or two is not an option.
Yes,
SQL Serverrounds time to3.(3)milliseconds:As you can see, these
DATETIME‘s differ by1second, and their binary representations differ by0x12C, that is300in decimal.This is because
SQL Serverstores thetimepart of theDATETIMEas a number of1/300second ticks from the midnight.If you want more precision, you need to store a
TIMEpart as a separate value. Like, store time rounded to a second as aDATETIME, and milliseconds or whatever precision you need as anINTEGERin another columns.This will let you use complex
DATETIMEarithmetics, like adding months or finding week days onDATETIME‘s, and you can just add or substract the milliseconds and concatenate the result as.XXXXXX+HH:MMto get validXMLrepresentation.