Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to TryParseExact a string containing just the 24-based hour?

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?

like image 460
Roman Starkov Avatar asked Dec 30 '11 19:12

Roman Starkov


1 Answers

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:

To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.

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.

like image 76
João Angelo Avatar answered Oct 05 '22 06:10

João Angelo