How to convert C# Datetime.Today, into Timestamp format 10/20/2011 12:00:00 in mysql?
-
Are you asking how to do this in C# or how to do this in Mysql?Polity– Polity2011-10-20 08:28:24 +00:00Commented Oct 20, 2011 at 8:28
-
Have you considered using parameterized queries instead?Mark Byers– Mark Byers2011-10-20 08:29:35 +00:00Commented Oct 20, 2011 at 8:29
5 Answers
If you want to get the date time as a string in that format then you can do...
string dt = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
See here for extra formatting options for the DateTime ToString method
Though from my understanding of MySQL it will accept a timestamp in the format yyyy-MM-dd HH:mm:ss. I would recommend doing this as it will ensure dates like 05/08/2011 are parsed correctly for the right month and day...
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
2 Comments
"MM/dd/yyyy HH:mm:ss" (according to OP question) and you get +1 from me :)Try this:
DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
and if you want more/other time formats, check this.
Comments
This Possibly may assist someone with the same approach and thought that I had:
To test directly in MYSQL Workbench:
INSERT into tblDemo VALUES (898,CURRENT_TIMESTAMP());
create table tblDemo (ScenarioID INT(10),
ProcessTime DATETIME DEFAULT CURRENT_TIMESTAMP() NOT NUll);
Now compile the string in your C# Code like so:
string query = "INSERT into tblDemo " +
"VALUES (" + ScenarioID + "," + " CURRENT_TIMESTAMP())";
Note the CURRENT_TIMESTAMP() in quotes in the above query
Output: '2021-03-04 17:52:30'