在日期时间 c# 中格式化字符串以插入到 MYSQL 日期时间列中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18705284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:58:20  来源:igfitidea点击:

format string in datetime c# to insert in MYSQL datetime column

c#mysql.net

提问by onik

I have code like this:

我有这样的代码:

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

When I see it in the DailyReporttable it shows me only the date ("10-10-2014 00:00:00:00"), so the time is ignored. How could i fix it? The column type is DateTime.

当我在DailyReport表格中看到它时,它只显示日期("10-10-2014 00:00:00:00"),所以时间被忽略了。我怎么能修好呢?列类型为DateTime.

采纳答案by Derrick

A quick/easy method to insert date or datetime into MySQL is to use the format 'yyyy-MM-dd', or datetime as 'yyyy-MM-dd H:mm:ss'.

将日期或日期时间插入 MySQL 的一种快速/简单的方法是使用格式“yyyy-MM-dd”或日期时间为“yyyy-MM-dd H:mm:ss”。

Try this

尝试这个

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

Make your SQL look like this.

让你的 SQL 看起来像这样。

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

回答by user2711965

Your line:

您的线路:

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

Shouldn't compile.

不应该编译。

I can only guess that you don't have DateTimeas type of your column in SQL Server, you should modify it to keep DateTimeand then pass a DateTime type object, not a string.

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

回答by Mike Perrenoud

This means that the underlying data type in the database must be Date. Change that to DateTimeand it will store the time as well.

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

回答by jeleel

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

The insert Statement will look kind of like this:

插入语句看起来像这样:

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