对于以下代码,我希望 result 等于 2,因为 MSDN 声明d"将月份中的日期表示为从 1 到 31 的数字.一位数day 的格式没有前导零.".
For the following code, I would expect result to equal 2, because the MSDN states that 'd' "Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero.".
DateTime myDate = new DateTime( 2009, 6, 4 );
string result = myDate.ToString( "d" );
但是,result 实际上等于 '6/4/2009' - 这是短日期格式(也是 'd').我可以使用dd",但这会添加一个前导零,这是我不想要的.
However, result is actually equal to '6/4/2009' - which is the short-date format (which is also 'd'). I could use 'dd', but that adds a leading zero, which I don't want.
要表明这是一个自定义格式说明符(与标准格式说明符相反),它必须是两个字符长.这可以通过添加空格(将显示在输出中)或在单个字母前添加百分号来实现,如下所示:
To indicate that this is a custom format specifier (in contrast to a standard format specifier), it must be two characters long. This can be accomplished by adding a space (which will show up in the output), or by including a percent sign before the single letter, like this:
string result = myDate.ToString("%d");
请参阅 文档
这篇关于格式化 .NET DateTime“日";没有前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!