SQL 服务器和 C# 中 DateTime 的毫秒数不相同
Milliseconds from DateTime in SQL Server and C# are not the same
我正在从 SQL 服务器的数据库中获取日期。
当我从数据库中获取 DateTime
并比较 C# 和 SQL 服务器中的毫秒数时。
我看他们不一样。
这是为什么?
SQL 服务器的 datetime
数据类型在毫秒级别不准确。
Official documentation 提供数据时间数据类型的属性列表。
在该列表中,您将找到以下行:
Accuracy Rounded to increments of .000, .003, or .007 seconds
您还会在同一页面中找到以下引用:
Note
Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.
如果您使用 DateTime2
而不是 DateTime
,您将获得 100 纳秒的精度,以及其他好处。
事实上,除非在需要保持向后兼容性的情况下,否则根本不应该使用 DateTime
,而只能使用较新的数据类型。
我正在从 SQL 服务器的数据库中获取日期。
当我从数据库中获取 DateTime
并比较 C# 和 SQL 服务器中的毫秒数时。
我看他们不一样。
这是为什么?
SQL 服务器的 datetime
数据类型在毫秒级别不准确。
Official documentation 提供数据时间数据类型的属性列表。
在该列表中,您将找到以下行:
Accuracy Rounded to increments of .000, .003, or .007 seconds
您还会在同一页面中找到以下引用:
Note
Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.
如果您使用 DateTime2
而不是 DateTime
,您将获得 100 纳秒的精度,以及其他好处。
事实上,除非在需要保持向后兼容性的情况下,否则根本不应该使用 DateTime
,而只能使用较新的数据类型。