JamesBlond JamesBlond -4 years ago 209
C# Question

DateTime.TryParseExact single second

I have time results from races in many different formats (more or less any combination of hour, minute, second and millisecond):

  • 01:22:51.15

  • 22:15.12

  • 15.0

  • 12:21

  • ...

I parse them with a list of valid formats and so far all the formats work except one: The single second format, e.g. "5".

For some reason the following list (containing "s" as the 1st item) does not help me to parse the string "5" into a DateTime, "25" works fine though.

var timeString = "5";
var timeFormats = new[] { "s", "s.f", "s.ff", "ss", "ss.f", "ss.ff", "m:ss", "m:ss.f", "m:ss.ff", "mm:ss", "mm:ss.f", "mm:ss.ff", "H:mm:ss", "H:mm:ss.f", "H:mm:ss.ff", "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff" };
DateTime timeValue;
DateTime.TryParseExact(timeString, timeFormats, null, DateTimeStyles.None, out timeValue);

Any idea why this does not work as I expect it to? Or is there a cleaner way to cover all these time formats without adding another nuget package...?

Answer Source

Because there is only one character in the format, it is being treated as the Sortable standard format, rather than as a custom format with seconds.

To change this, prefix the custom format with a % character, as in "%s". See "Using single custom format specifiers".

Also, recognize that if these are actual elapsed times of races, TimeSpan is a more appropriate data structure than DateTime. Be careful when switching, as not all formatting tokens are identical between the two objects. In particular, TimeSpan uses h for hours, not H. See Custom TimeSpan Format Strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download