First of all: a '
Tue Aug 9 00:00:03 2016
' date
cannot be converted into '
2016-10-09 00:00:03
', because due to August is 8. month in the year.
Second of all, all what you need to do is:
string inputDate = "Tue Aug 9 00:00:03 2016";
string inputFormat = "ddd MMM d hh:mm:ss yyyy";
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US");
DateTime resultDate = DateTime.ParseExact(inputDate, inputFormat, provider);
But(!), i'd suggest to use
DateTime.TryParse[
^] or
DateTime.TryParseExact[
^] method.
DateTime resultDate1;
if (DateTime.TryParseExact(inputDate, inputFormat, provider, System.Globalization.DateTimeStyles.None, out resultDate1))
{
Console.WriteLine("A result date is '{0}'", resultDate1);
}
else
{
Console.WriteLine("String to date conversion failed!");
}
[EDIT]
Using
DateTime.TryParseExact
, you can loop through the set of formats, ie.:
string inputDate = "Tue Aug 10 00:00:03 2016";
string[] inputFormats = new string[] {"MMM d hh:mm:ss yyyy", "MMM dd hh:mm:ss yyyy"};
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US");
DateTime resultDate = new DateTime(1900,1,1);
foreach(string format in inputFormats)
{
if (DateTime.TryParseExact(inputDate.Substring(4,inputDate.Length-4), format, provider, System.Globalization.DateTimeStyles.None, out resultDate))
{
Console.WriteLine("A result date is '{0}'", resultDate);
break;
}
}
if(resultDate==new DateTime(1,1,1))
{
Console.WriteLine("String to date conversion failed. Unknown format!");
}