在datetime c#中格式化字符串以在MYSQL datetime列中插入

我有这样的代码:

AutoParkDataDataContext Db = new AutoParkDataDataContext(); Dailyreport dailyRep = new Dailyreport(); string time = Convert.ToDateTime("10-10-2014 15:00:00"); dailyRep.order_time = time; Db.Dailyreports.InsertOnSubmit(dailyRep); Db.SubmitChanges(); 

当我在DailyReport表中看到它时, DailyReport显示日期("10-10-2014 00:00:00:00") ,因此时间被忽略。 我该怎么办呢? 列类型是DateTime

将日期或日期时间插入MySQL的快速/简单方法是使用格式’yyyy-mm-dd’或日期时间为’yyyy-mm-dd hh:mm:ss’。

试试这个

  DateTime theDate = DateTime.Now; theDate.ToString("yyyy-MM-dd H:mm:ss"); 

让你的SQL看起来像这样。

  insert into mytable (date_time_field) value ('2013-09-09 03:44:00'); 

你的路线:

 string time = Convert.ToDateTime("10-10-2014 15:00:00"); 

不应该编译。

我只能猜测你没有将DateTime作为SQL Server中列的类型,你应该修改它以保留DateTime ,然后传递DateTime类型对象,而不是字符串。

这意味着数据库中的基础数据类型必须是Date 。 将其更改为DateTime ,它也将存储时间。

 DateTime dateTimeVariable = DateTime.Now; string date = dateTimeVariable.ToString("yyyy-MM-dd H:mm:ss"); 

insert语句看起来像这样:

 string InsertQuery = "INSERT INTO table( `fieldName` ) VALUES ( '" + date + "' )";