开发者

DateTime.TryParseExact not working as expected

开发者 https://www.devze.com 2023-01-18 11:12 出处:网络
why does this not work? DateTime.TryParseExact(text, \"H\", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out value);

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 work开发者_如何转开发s:

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

Anybody knows the cause?

Thanks.


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);


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消