gpt4 book ai didi

c# - 为什么 DateTime.ToString ("h") 导致异常?

转载 作者:IT王子 更新时间:2023-10-29 04:33:24 25 4
gpt4 key购买 nike

打开监 window 口

new DateTime(2010,01,01).ToString("h")

给予:

new DateTime(2010,01,01).ToString("h") threw an exception of type System.FormatException

然而...

new DateTime(2010,01,01).ToString("h ")

给出:“12”

那么为什么额外的空格会阻止这种格式异常的发生呢?这是错误吗?

最佳答案

因为它认为这是一个standard format string而不是 custom one , 由于是单个字符。

解决此问题的更好方法是使用 %:

string text = DateTime.Now.ToString("%h");

来自自定义格式字符串的文档:

A custom date and time format string consists of two or more characters. Date and time formatting methods interpret any single-character string as a standard date and time format string. If they do not recognize the character as a valid format specifier, they throw a FormatException. For example, a format string that consists only of the specifier "h" is interpreted as a standard date and time format string. However, in this particular case, an exception is thrown because there is no "h" standard date and timeformat specifier.

To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.

For example, "%h" is interpreted as a custom date and time format string that displays the hour represented by the current date and time value. You can also use the " h" or "h " format string, although this includes a space in the result string along with the hour. The following example illustrates these three format strings.

关于c# - 为什么 DateTime.ToString ("h") 导致异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3459677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com