Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Input string was not in a correct format" error when trying to display hour portion with 'h'

I am trying to display a datetime field using the hour portion only without leading zeros for the single digit hours as in: return string.Format("{0:h}", MyDateTimefield) but I get a "Input string was not in a correct format" error. Why?

return string.Format("{0:hh}", MyDateTimefield) works. Looking for the correct format and not a workaround.

like image 859
Tony_Henrich Avatar asked Jan 26 '12 18:01

Tony_Henrich


2 Answers

From the pertinent docs:

If the "h" format specifier is used without other custom format specifiers, it is interpreted as a standard date and time format specifier and throws a FormatException. For more information about using a single format specifier, see Using Single Custom Format Specifiers later in this topic.

Following that link gets you to:

To use any of the custom date and time format specifiers as the only specifier in a format string […], include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.

like image 172
millimoose Avatar answered Nov 18 '22 00:11

millimoose


From this link using h is the correct format for hour without leading 0. Very interesting.. the following all seem to work:

return string.Format("{0: h}", MyDateTimefield)
return string.Format("{0:h }", MyDateTimefield)
return string.Format("{0:h:m}", MyDateTimefield)

But as soon as you put in return string.Format("{0:h}", MyDateTimefield) it throws an exception.

As for why, I'm not sure. If you're okay with a space the first 2 lines should work.

like image 43
Lester Avatar answered Nov 18 '22 00:11

Lester