According to MSDN , d 格式说明符输出 TimeSpan.Days 属性。在 .ToString() 方法中使用时,这似乎是正确的:
TimeSpan.FromDays(1).ToString("%d")
但是,当在 String.Format 中使用时,说明符会抛出异常:
String.Format("{0:d}", TimeSpan.FromDays(1))
'String.Format("{0:d}", TimeSpan.FromDays(1))' threw an exception of type 'System.FormatException'
base {System.SystemException}: {"Input string was not in a correct format."}
dd 说明符工作得很好,但给出了一个前导零(如预期的那样)。
为什么 d 说明符抛出异常?
请您参考如下方法:
您缺少 %:
string.Format("{0:%d}", TimeSpan.FromDays(1))
根据您链接的文章(以及您复制的示例):
If the "d" custom format specifier is used alone, specify "%d" so that it is not misinterpreted as a standard format string.
