I have a date that I need to get into a DateTime
object. In my code below I set the filedate
to the date string that I get and then try two different formats (patern
and patern2
. It does not recognize the format and always falls down to the else block and I dont get the datetime object as I need it. I got the format string set up using the specifiers I found on MSDN on this page..
string filedate = "Tue Aug 12 16:01:29 CDT 2014";
string patern = "ddd MMM d hh:mm:ss CDT yyyy";
string patern2 = "ddd MMM dd hh:mm:ss CDT yyyy";
DateTime dat;
CultureInfo enUS = new CultureInfo("en-US");
string outString = "";
if (DateTime.TryParseExact(filedate, patern, enUS, System.Globalization.DateTimeStyles.None, out dat))
{
outString = (dat.ToShortDateString() + " " + dat.ToShortTimeString());
}
else if (DateTime.TryParseExact(filedate, patern2, enUS, System.Globalization.DateTimeStyles.None, out dat))
{
outString = (dat.ToShortDateString() + " " + dat.ToShortTimeString());
}
else
{
outString = filedate.Trim(); //always falling to here
}
Three problems:
hh
means hour of 12-hour clock; 16 isn't a valid valueCDT
part as you want it as a literalI suspect you want:
"ddd MMM d HH:mm:ss 'CDT' yyyy";
Additionally, if this is always in English, you probably want to use CultureInfo.InvariantCulture
.
Finally, I suspect this is only going to be valid in the summer... in winter I'm guessing you'll have CST
instead. Unfortunately this is a horrible format... you may well want to use string operations to strip out the CST/CDT (or whatever it is - will it always be central time?) before parsing. As far as I'm aware, there's no support for parsing those.
See more on this question at Stackoverflow