从C#中的SQL数据库读取DateTime值时没有毫秒值 [英] No milliseconds value when reading DateTime values from a SQL database in C#

查看:395
本文介绍了从C#中的SQL数据库读取DateTime值时没有毫秒值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL Server中存储了高精度的日期,例如

I have high precision dates stored in an SQL server, e.g.

2009-09-15 19:43:43.910

但是,当我将该值转换为DateTime时,所得DateTime值的毫秒值是0:

However when I convert that value into a DateTime the miliseconds value of the resulting DateTime value is 0:

reader["Timestamp"] = 15/09/2009 19:43:43.000

让这些DateTime值精确到毫秒很重要-做到这一点的最佳方法是什么?

Having these DateTime values in precision down to milliseconds is very important to me - what is the best way of doing this?

更新::这是执行转换的代码:

UPDATE: This is the code that performs the conversion:

DateTime myDate = (DateTime)reader[Timestamp"];

<$ c $没什么特别的c> SELECT 语句,实际上它是 SELECT * -没有花哨的演员表或其他内容

There is nothing special about the SELECT statement, in fact it is a SELECT * - no fancy casts or anything

看来, SqlDataReader 返回的DateTime对象根本没有填充毫秒值

It appears that the DateTime object returned by the SqlDataReader simply is not populated with the Millisecond value

推荐答案

这是我尝试解决此问题的方法:

Here's how I'd try to troubleshoot this:


  1. 逐步进入调试器并查看以reader [Timestamp]的类型和值。如果类型不是SqlDateTime,那会让我感到怀疑-然后,我将查看查询以找出为什么该列返回的是另一种类型而不是DATETIME(或DATETIME2等)

  1. step through in the debugger and look at the type and value of reader[Timestamp"]. If the type is not SqlDateTime, that would make me suspicious-- I'd then look at the query to figure out why that column was returning another type instead of DATETIME (or DATETIME2, etc.)

如果该值为SqlDateTime并且确实包含毫秒,那么我将视类型转换为问题的根源。为了验证这一点,我尝试(在调试器或代码中)SqlDataReader.GetDateTime()和SqlDataReader.GetSqlDateTime()来查看它们是否返回正确的结果。诚然,这似乎不太可能成为问题的根源-投射应该可以正常工作。

if that value is SqlDateTime and it does contains milliseconds, then I'd look at the cast as the source of the problem. To validate this, I'd try (in debugger or code) SqlDataReader.GetDateTime() and SqlDataReader.GetSqlDateTime() to see if either returns the correct result. This admittedly seems really unlikely as source of the problem-- casting should work fine.

如果#1中的值是SqlDateTime但不包含毫秒,那么我将查看数据库中的上游问题-换句话说,您的查询返回没有毫秒的东西。当您在Management Studio中执行完全相同的查询时,您看到毫秒了吗?

if that value from #1 is SqlDateTime but contains no milliseconds, then I'd look to an upstream problem in the database-- in other words your query is returning something without milliseconds. when you execute the exact same query in Management Studio, do you see milliseconds?

我的猜测是这是一个查询相关的问题。但是我很感兴趣找到更多。

My guess is this is a query-related issue. But am intrigued to find our more.

这篇关于从C#中的SQL数据库读取DateTime值时没有毫秒值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆