Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date/time string value to .NET DateTime

i've this string example value: Sun, 09 May 2010 11:16:35 +0200

I've to insert it into MySql Date/Time field.

How can i convert it into .NET format (or Mysql format), so i can make my INSERT INTO mydate='2010-05-09 11:16:35' ? Thank you !

like image 751
stighy Avatar asked Dec 10 '22 16:12

stighy


2 Answers

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

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

like image 111
Robert Harvey Avatar answered Dec 22 '22 23:12

Robert Harvey


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

Don't be tempted to do something like:

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

It's much better to build a parameterized query instead, not just in this case. It also makes sure that if you're trying to insert/update text, you're able to handle quotes correctly (instead of risking a sql injection possibility)

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();
}
like image 32
Sander Rijken Avatar answered Dec 22 '22 22:12

Sander Rijken