当存储在SQL Server中的我的DateTime变化毫秒我的、SQL、Server、DateTime

2023-09-02 10:45:37 作者:疯到世界都崩溃

我有个约会时候,我产生这样的:

I have a date time that I generate like this:

DateTime myDateTime = DateTime.Now;

我把它存储在数据库中(在的DateTime 键入列)与实体框架。然后我用的OData(WCF数据服务)获取它。

I then store it in the database (in a DateTime typed column) with Entity Framework. I then retrieve it with OData (WCF Data Services).

当它进入了的TimeOfDay值: 09:30:03.0196095

When it goes in the TimeOfDay value is: 09:30:03.0196095

当它出来了的T​​imeOfDay值: 09:30:03.0200000

When it comes out the TimeOfDay value is: 09:30:03.0200000

这样做的实际效果使得它,这样的毫秒它被保存和20是在重新加载之前被视为19。

The net effect of this makes it so that the Milliseconds are seen as 19 before it is saved and 20 after it is re-loaded.

所以,当我做我的code后,一个比较,它失败的地方应该是平等的。

So when I do a compare later in my code, it fails where it should be equal.

难道SQL服务器没有太多precision作为.NET?或者是实体框架或OData的是搞乱这个吗?

Does SQL Server not have as much precision as .NET? Or is it Entity Framework or OData that is messing this up?

我只是截断关闭毫秒(我并不真的需要它们)。不过,我想知道为什么会这样。

I will just truncate off the milliseconds (I don't really need them). But I would like to know why this is happening.

推荐答案

这真的取决于SQL服务器正在使用的版本。

This really depends on the version of SQL server you are using.

日期时间字段的分辨率是到3位小数:例如: 2011-06-06 23:59:59.997 ,仅accuracte内3.33毫秒

The resolution of the date time field is to 3 decimal places: For example: 2011-06-06 23:59:59.997 and is only accuracte to within 3.33 ms.

在你的情况, 09:30:03.0196095 被四舍五入为 09:30:03.020 的存储

In your case, 09:30:03.0196095 is being rounded up to 09:30:03.020 on storage.

开始与SQL Server 2008,添加其他数据类型,以提供更多的细节,如DATETIME2其中有多达7位小数,并精确到100纳秒之内。

Beginning with SQL 2008, other data types were added to provide more detail, such as datetime2 which has up to 7 decimal places and is accurate to within 100ns.

请参阅下面的详细信息: http://www.karaszi.com/SQLServer/info_datetime.asp

See the following for more information: http://www.karaszi.com/SQLServer/info_datetime.asp

我认为最好的办法是提供舍入到第二之前,将其存储在SQL服务器,如果毫秒是不重要的。

I think your best bet is to provide the rounding to the second PRIOR to storing it in SQL server if the milliseconds is unimportant.