Reputation: 941
I am trying to convert the date string Oct 21 2014 1:00 AM
to 2014-10-21 01:00:00
or something that SQL Server can understand.
Upvotes: 0
Views: 588
Reputation: 74
Please see answer here.
Converting a String to DateTime
DateTime.ParseExact may work for you to convert in DateTime and then you can use ToString(<format>)
with format to convert it in required string.
Upvotes: 0
Reputation: 3212
I'd argue that if you're using ADO.NET to communicate with your SQL Server, you shouldn't use a formatted date string as a query parameter. You should instead use a DateTime
object. You can get it from your string by using either the DateTime.Parse
or DateTime.TryParse
methods:
DateTime date = DateTime.Parse("Oct 21 2014 1:00 AM"); // Use this as your query parameter.
However if you do decide to go with using a formatted string, the simplest way would be first parse it to as shown above, then you can use ToString
with a format string overload, to format your date as you want.
To get your example format:
DateTime date = DateTime.Parse("Oct 21 2014 1:00 AM");
string formatted = DateTime.ToString("yyyy-MM-dd hh:mm:ss"); // 2014-10-21 01:00:00
Upvotes: 2
Reputation: 15112
var dateString = "Oct 21 2014 1:00 AM";
DateTime result;
DateTime.TryParse(dateString, out result);
var sqlDate = result.ToString("yyyy-MM-dd HH:mm:ss");
Upvotes: 4