Reputation: 11
I have a flat file that has some dates coming in as m/d/yy and some as mm/dd/yy. I am trying to convert them all to MM/dd/yy with no success. The code is below. Can somebody tell me what I'm doing wrong.
StudentRec.birthdate = fields[i];
string[] format = { "MM/dd/yy" };
DateTime dateValue;
if (StudentRec.birthdate.Length > 0)
{
if (!DateTime.TryParseExact(StudentRec.birthdate, format,
new CultureInfo("en-US"),
DateTimeStyles.AllowWhiteSpaces ,
out dateValue))
{
Console.WriteLine(StudentRec.birthdate);
throw new MyException("Birthdate is not valid ", o, strCNFileErr);
}
}
Upvotes: 1
Views: 74
Reputation: 10055
You just need to add the second valid date format. It will attempt each one until it succeeds.
StudentRec.birthdate = fields[i];
string[] format = { "MM/dd/yy", "M/d/yy" }; // Valid formats.
DateTime dateValue;
if (StudentRec.birthdate.Length > 0)
{
if (!DateTime.TryParseExact(StudentRec.birthdate, format,
new CultureInfo("en-US"),
DateTimeStyles.AllowWhiteSpaces ,
out dateValue))
{
Console.WriteLine(StudentRec.birthdate);
throw new MyException("Birthdate is not valid ", o, strCNFileErr);
}
}
Note: The first format that works will return.
Upvotes: 2