views:

91

answers:

4

Hi guys, 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 !

+6  A: 

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

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

Robert Harvey
You just got me by seconds ;-)
Erick
+1  A: 

DateTime.Parse() is quite the easiest that comes in my mind in fact.

Erick
+2  A: 
System.DateTime  dateTime = System.DateTime.Parse(YourDate)

Then you could do whatever you want like get it in seconds, or whatever.

PSU_Kardi
+2  A: 

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();
}
Sander Rijken
-1 for the anonymous strategic downvotes. And you essentially gave the same answer as the others.
Robert Harvey
I wonder what made you think I did that? My other point is that the question indicates that he's trying to concatenate a SQL query together, which is just a bad practice in my opinion.
Sander Rijken
So the OP downvoted everyone? Without explanation?
Robert Harvey
I have no idea what happened.
Sander Rijken
OK. I'll take your word for it.
Robert Harvey
Edited my answer slightly again, to indicate that my main point was the query
Sander Rijken
I guys, no i'haven't downvoted nobody.. Thank you for your answer!
stighy