Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

mysql

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 DailyReport table 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.

like image 912
onik Avatar asked Sep 09 '13 19:09

onik


People also ask

What is T and Z in DateTime C?

A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime. ToString using the 'z' format specifier, which will include a local time zone offset in the output.

How do I get yyyyMMddHHmmss in C#?

You can use a custom format string: DateTime d = DateTime. Now; string dateString = d. ToString("yyyyMMddHHmmss");


2 Answers

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'.

Try this

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

Make your SQL look like this.

insert into mytable (date_time_field) value ('2013-09-09 03:44:00');
like image 109
Derrick Avatar answered Oct 03 '22 11:10

Derrick


Your line:

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

Shouldn't compile.

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

like image 42
user2711965 Avatar answered Oct 03 '22 10:10

user2711965