0

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.

Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
LearningJrDev
  • 911
  • 2
  • 8
  • 27

3 Answers3

4

Use DateTime.TryParse

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");
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
2

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
Gediminas Masaitis
  • 3,172
  • 14
  • 35
  • Given the string provided and assuming it won't change, this is the correct approach. – Gabe Mar 08 '16 at 22:01
0

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.

Community
  • 1
  • 1
Mitesh
  • 74
  • 1
  • 7
  • `DateTime.ParseExact` is only useful when you know the exact format beforehand, if you do not - it will fail. Also, assuming the string provided is the way the data will always be received, even `TryParse()` is redundant and he should use `Parse()` insead. `ParseExact` is only useful when the format is uncommon or of a different culture variation and won't parse with any other method. _Always_ use `.Parse()` or `.TryParse()` before resorting to `.ParseExact()`. – Gabe Mar 08 '16 at 21:54