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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With