I'm trying to convert user entered times into TimeSpans. Because TimeSpan does not have a TryParseExact method I'm using the one in DateTime and converting the output from it.
The formats I want to handle are: 04:00, 0400, 4:00, and 400. The first three aren't a problem and correspond to the first three cases in the if/else structure in the method below. The forth could correspond to either of the last two, but neither is working.
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
CultureInfo enUS = new CultureInfo("en-US");
DateTime parsedDate = new DateTime();
string userInput = (string)e.Value;
if (DateTime.TryParseExact(userInput, "HH:mm", enUS, DateTimeStyles.None, out parsedDate))
{
e.Value = parsedDate.TimeOfDay;
e.ParsingApplied = true;
}
else if (DateTime.TryParseExact(userInput, "HHmm", enUS, DateTimeStyles.None, out parsedDate))
{
e.Value = parsedDate.TimeOfDay;
e.ParsingApplied = true;
}
else if (DateTime.TryParseExact(userInput, "H:mm", enUS, DateTimeStyles.None, out parsedDate))
{
e.Value = parsedDate.TimeOfDay;
e.ParsingApplied = true;
}
else if (DateTime.TryParseExact(userInput, "hmm", enUS, DateTimeStyles.None, out parsedDate))
{
e.Value = parsedDate.TimeOfDay;
e.ParsingApplied = true;
}
else if (DateTime.TryParseExact(userInput, "Hmm", enUS, DateTimeStyles.None, out parsedDate))
{
e.Value = parsedDate.TimeOfDay;
e.ParsingApplied = true;
}
}