简体   繁体   English

C#时间到SQL日期时间

[英]c# time to sql date time

I am not able to convert the c# date time 7/31/2017 3:13:49 PM to SQL date time while inserting the records to the database. 将记录插入数据库时​​,我无法将C#日期时间7/31/2017 3:13:49 PM转换为SQL日期时间。

I am doing this using 我正在使用

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

But it's giving me the error. 但这给了我错误。

String was not recognized as a valid DateTime. 无法将字符串识别为有效的DateTime。

将其更改为年/月/日后,这将有所帮助!

var sqlDate = finalDate.Date.ToString("yyyy-MM-dd HH:mm:ss");

Your dateformat says 'year-month-day' while your date is 'month/day/year', that can't be right. 您的日期格式为“年-月-日”,而日期为“月/日/年”,则可能不正确。 Either change your dateformat or your date's formatting. 更改日期格式或日期格式。

This should work: 这应该工作:

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

将查询更改为

insert into table_name (column1) values ('" + dt.Value.ToString("yyyy-MM-dd") + "')

Try the method DateTime.ParseExact and specify The date format that is suitable for you, here is an example from MSDN ( https://msdn.microsoft.com/fr-fr/library/w2sa9yss(v=vs.110).aspx ) : 尝试使用方法DateTime.ParseExact并指定适合您的日期格式,这是MSDN的示例( https://msdn.microsoft.com/fr-fr/library/w2sa9yss(v=vs.110).aspx ):

var dateString = "06/15/2008";
var format = "d";
try {
     var result = DateTime.ParseExact(dateString, format, 
     CultureInfo.InvariantCulture);
     Console.WriteLine("{0} converts to {1}.", dateString, 
     result.ToString());
     }
  catch (FormatException) 
  {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }

The .Net DateTime maps directly to SQL Server DateTime . .Net DateTime 直接映射到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. 这意味着您完全不必担心显示格式,因为DateTime 没有显示格式。
All you need to do is pass the instance of the DateTime struct as a parameter to the SqlCommand : 您需要做的就是将DateTime结构的实例作为参数传递给SqlCommand

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

Bonus reading: How do I create a parameterized SQL query? 奖励阅读: 如何创建参数化的SQL查询? Why Should I? 我为什么要?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM