C#时间到SQL日期时间 [英] c# time to sql date time

查看:110
本文介绍了C#时间到SQL日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将记录插入数据库时​​,我无法将c#日期时间 2017/7/31下午3:13:49 转换为SQL日期时间。

I am not able to convert the c# date time7/31/2017 3:13:49 PM to SQL date time while inserting the records to the database.

我正在使用

DateTime dt = DateTime.Parse("11/23/2010");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
DateTime finalDate = DateTime.Parse(toSqlDate);

但这给了我错误。


字符串未被识别为有效的DateTime。

String was not recognized as a valid DateTime.


推荐答案

.Net DateTime 直接映射到SQL Server DateTime 。这意味着您完全不必担心显示格式,因为 DateTime 没有显示格式。

您需要做的就是传递<$ c $的实例。 c> DateTime 结构作为参数 SqlCommand

The .Net DateTime maps directly to SQL Server DateTime. This means you don't need to worry about the display format at all, since DateTime does not have a display format.
All you need to do is pass the instance of the DateTime struct as a parameter to the SqlCommand:

SqlCommand.Parameters.Add("@DateTimeParam", SqlDbType.DateTime).Value = dt; 

奖金阅读:如何创建参数化的SQL查询?我为什么要这么做?

这篇关于C#时间到SQL日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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