It just doesn’t want to work:
DateTime time;
DateTime.TryParseExact("17", "HH", ..., out time);
// works fine
DateTime.TryParseExact("9", "HH", ..., out time);
// works fine, but 9 doesn't match HH (nor should it)
DateTime.TryParseExact("9:", "H':'", ..., out time);
// works fine
DateTime.TryParseExact("9", "H", ..., out time);
// exception: "Input string was not in a correct format"
The fact that #3 works offers an obvious work-around, but it’s one of those things that would make me go “WTF” if I saw it in someone else’s code. Is TryParseExact buggy or something?
You can use
DateTime.TryParseExact("5", "%H", null, DateTimeStyles.None, out time).To parse the hour in a 24-hour clock without leading zero one could be tempted to use just the
"H"format, but a custom date and time format must consist of two or more characters, which would lead to"H"being interpreted as a standard date and time format, resulting in a format exception.From MSDN on Custom Date and Time Format Strings:
I prefer to include the
%sign before since I find that a space before or after may be interpreted as a typing mistake and be removed by someone else.