"Line input error was not in the correct format" when trying to display part of the hour with "h"

I am trying to display the datetime field using the hour part, only without leading zeros for one hour digit, as in: return string.Format("{0:h}", MyDateTimefield) , but I get the error "The input string is not in the correct format " Why?

return string.Format("{0:hh}", MyDateTimefield) works. Finding the right format, not a workaround.

+6
source share
2 answers

From the relevant documents :

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

Following this link, you:

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

+15
source

From this link using h is the correct format for an hour without a leading 0. Very interesting .. the following 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 type return string.Format("{0:h}", MyDateTimefield) , it throws an exception.

As for me, I'm not sure. If you are ok with a space, the first 2 lines should work.

+2
source

Source: https://habr.com/ru/post/906966/


All Articles