C# 从SQL读取器获取正确的日期时间格式
问题:我得到的SQL数据库的列类型为C# 从SQL读取器获取正确的日期时间格式,c#,sql,datetime,datetime-format,datetimeoffset,C#,Sql,Datetime,Datetime Format,Datetimeoffset,问题:我得到的SQL数据库的列类型为datetime,我正在尝试获取datetime类型的c#API变量的值 datetime format in SQL DB: 2011-11-14 00:00:00.000 // So that equals: yyyy - MM - dd HH:mm:ss.ttt 以下是我为获得正确价值所做的一些尝试: MyClass.MyProperty= Convert.ToDateTime(reader.
datetime
,我正在尝试获取datetime
类型的c#API变量的值
datetime format in SQL DB: 2011-11-14 00:00:00.000 // So that equals:
yyyy - MM - dd HH:mm:ss.ttt
以下是我为获得正确价值所做的一些尝试:
MyClass.MyProperty= Convert.ToDateTime(reader.GetSqlDateTime(0));
MyClass.MyProperty= Convert.ToDateTime(reader.GetDateTime(0));
MyClass.MyProperty= Convert.ToDateTime(reader.GetValue(0));
MyClass.MyProperty= DateTime.ParseExact(reader.GetValue(0).ToString(), "yyyy - MM - dd HH:mm:ss.ttt", CultureInfo.InvariantCulture);
每次尝试编译时,我都会得到以下输出:
0001-01-01T00:00:00
我还尝试与DateTimeOffset
结合使用,从字符串中的DB中获取值,然后将其转换为Datetime,但是VS
更新:
我尝试通过服务器在数据库上执行SQL语句,发现我的配置文件的UserGuid在所选列中没有任何时间。(我在最初测试SQL语句时使用了不同的用户凭据)我修复了一些问题并进行了更多的调试,现在连接和读卡器正常工作。我在格式化tho时仍然有问题
DB value: 2014-08-07 00:00:00.000
Output: 8/7/2014 12:00:00 AM
我试图告诉它如何使用ParseExact格式化DateTime格式,但它引发了以下异常:
System.FormatException' in mscorlib.dll
Additional information: String was not recognized as a valid DateTime.
以下是我为整个阅读器编写的代码:
while (reader1.Read())
{
newUsagePlan.PlanValidityFrom = DateTime.ParseExact(Convert.ToString(reader1.GetValue(0)), "yyyy - MM - dd HH:mm:ss.ttt", CultureInfo.InvariantCulture);
string lol1 = reader1.GetValue(0).ToString(); // Output: "8/7/2014 12:00:00 AM"
string lol2 = reader1.GetSqlDateTime(0).ToString(); // Output: "8/7/2014 12:00:00 AM"
}
最终结论:
我现在很容易地解决了这个问题,只需使用以下方法:
string sqlFormattedDate = reader1.GetDateTime(0).ToString("yyyy-MM-dd HH:mm:ss.fff");
并获得了所需的输出:2014-08-07 00:00:00.000
一条建议:尽量不要在单个项目中处理生产和开发数据库,当数据库数据中存在不一致且您没有意识到时,它会让您的大脑崩溃。干杯:)您获得了哪些成果?你的SQL和你在同一个时区吗?我想你的问题是重复的,你能在你的读者周围放更多的代码吗?因此,我们可以看到您正在调用的select etc,它可能返回空值-如果您直接在SQL中运行相同的查询会发生什么情况?如果
reader.GetSqlDateTime(0)
返回一个字符串,那么这可以毫无问题地转换为DateTime
。您的返回值可能是问题所在,您可以调试并查看其中的值吗?您得到了什么输出?你的SQL和你在同一个时区吗?我想你的问题是重复的,你能在你的读者周围放更多的代码吗?因此,我们可以看到您正在调用的select etc,它可能返回空值-如果您直接在SQL中运行相同的查询会发生什么情况?如果reader.GetSqlDateTime(0)
返回一个字符串,那么这可以毫无问题地转换为DateTime
。您的返回值可能就是问题所在,您可以调试并查看其中的值吗?