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 !
The MSDN documentation on the DateTime.Parse()
method describes in detail how to do this.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
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();
}
System.DateTime dateTime = System.DateTime.Parse(YourDate)
Then you could do whatever you want like get it in seconds, or whatever.
DateTime.Parse() is quite the easiest that comes in my mind in fact.
精彩评论