I have user typed times that need parsing into DateTime or TimeSpan (the date is not important). For example need to be able to interpret
“8a”, “0800”, “8am”, “8 am”,”8:00 a”,”8:00 am” => as “08:00”
I have tried the DateTime.ParseExact method, but it relies on having a colon separator between hours and minutes. Hence fails on the first 4 cases above. TimeSpan also relies on the colon.
How can I go about creating a relatively robust way of handling the multiple ways of users entering times? One idea was to create an exhaustive listing of formatting possibilities for System.Globalization.DateTimeFormatInfo. But am unsure of how to handle the character ‘a’ or ‘am’ etc.
Ideas please.
The first four cases are fine:
DateTime.ParseExact(“8a”.Replace(“a”,”am”),”htt”,
System.Globalization.CultureInfo.CurrentCulture);
DateTime.ParseExact(“0800″,”HHmm”,
System.Globalization.CultureInfo.CurrentCulture);
DateTime.ParseExact(“8am”,”htt”,
System.Globalization.CultureInfo.CurrentCulture);
am”,”h tt”,
System.Globalization.CultureInfo.CurrentCulture);
Have a look at this for different toString matches