Convert date / time value to .NET DateTime

I have this value as an example string: Sun, May 09, 2010 11:16:35 AM +0200

I need to insert it into the MySql Date / Time field.

How can I convert it to .NET format (or Mysql format) so that I can make my INSERT INTO mydate='2010-05-09 11:16:35' ? Thanks!

+4
source share
4 answers

First you need to use DateTime.Parse() to create a .NET DateTime object from a string value, as noted by others.

Resist the temptation to do something like:

 var sql = "INSERT INTO MyTable VALUES(" + someDate.ToString() + ")"; 

It is much better to build a parameterized query, and not just in this case. It also ensures that if you try to insert / update text, you will be able to handle quotes correctly (instead of risking the possibility of sql injection)

 using (var conn = new MySqlConnection(connectString)) using (var cmd = new MySqlCommand("INSERT INTO mytable VALUES (1, 2, @theDate)", conn)) { cmd.Parameters.AddWithValue("@theDate", someDate); cmd.ExecuteNonQuery(); } 
+4
source

The MSDN documentation on the DateTime.Parse() method describes in detail how to do this.

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

+7
source
 System.DateTime dateTime = System.DateTime.Parse(YourDate) 

Then you could do whatever you want to get it in seconds or something else.

+2
source

DateTime.Parse () is the easiest thing that comes to my mind.

+1
source

Source: https://habr.com/ru/post/1309355/


All Articles