c# time to sql date time

自作多情 提交于 2019-11-28 11:35:20

问题


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.

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.


回答1:


After changing it to year/month/date this can help!

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



回答2:


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");



回答3:


Change query to

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



回答4:


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) :

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);
  }



回答5:


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; 

Bonus reading: How do I create a parameterized SQL query? Why Should I?



来源:https://stackoverflow.com/questions/45414955/c-sharp-time-to-sql-date-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!