I had posted a question on DateTime to String conversion, I got many satisfying answers for that .. so I thank StackOverflow very much ..
Here is one more problem of String
You can use the DateTime.ParseExact
overload that takes a list of formats:
private static string[] formats = new string[]
{
"MM/dd/yyyy HH:mm:ss tt",
"MM/dd/yyyy HH:mm:ss",
"M/dd/yyyy H:mm:ss tt",
"M/dd/yyyy H:mm:ss"
};
private static DateTime ParseDate(string input)
{
return DateTime.ParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
This will throw a FormatException
if the passed string does not match any of the given formats. Notice that the formats expecting AM/PM should appear before identical formats without AM/PM ("MM/dd/yyyy HH:mm:ss tt"
comes before "MM/dd/yyyy HH:mm:ss"
).
Update
As Henk points out in the comments, the same functionality is available when using TryParseExact
which removes exception situation. Also, paired with nullable types this can be made a bit cleaner:
private static DateTime? ParseDate(string input)
{
DateTime result;
if (DateTime.TryParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return result;
}
return null;
}
Now it will simply return a null reference if it fails to parse the input.