views:

73

answers:

4

why does this not work?

DateTime.TryParseExact(text, "H", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out value);

I want to parse an Time value only providing the hour part, but it throws a FormatException.

On the other hand, this works:

DateTime.TryParseExact(text, "HH", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out value)

Anybody knows the cause?

Thanks.

A: 

I guess this means that TryParseExact does not manage to fit the hour part into a single char, and that is understandable enough to me since hour will either be 12 or 24 hour based.

Øyvind Bråthen
Even if text is only "1", it won't work.
Lasse V. Karlsen
No, thats not how custom format strings work - The "H" custom format specifier represents the hour as a number from 0 through 23.
AHM
A: 

Without more specific information, the DatTime you're constructing can't determine AM / PM given the input. H would only allow a value of 1 - 12, leaving ambiguity. The HH provides the extra info.

DarkBobG
No, thats not what "H" means, you are thinking about "h" (lowercase). The difference between "H" and "HH" is supposed to be wether or not hours are printed with or without leading zeroes
AHM
Ah, true enough. Jumped to conclusion when I tested it and got the error without digging further. Thanks for clearing that up :D
DarkBobG
+2  A: 

Okay, I had to look this one up - it seems like it should be working, but it does not because the custom format string is not valid. A custom format string needs to be at least two characters wide - see:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers

So, according to the documentation, you can fix this by using this code:

DateTime.TryParseExact(text, "%H", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out value);
AHM
Great. That was it. Thanks!
Carles
A: 

The format specifier you pass to DateTime.TryParseExact needs to exactly match the string you are parsing.

E.g. passing "15:20" with format of "H" will fail, because there is other content in the string.

Either parse the whole string and use DateTime.Hour to just get the hour, or create a string with just the hour part and use Int32.Parse.

Richard