格式.NET DateTime“Day”没有前导零 [英] Format .NET DateTime "Day" with no leading zero

查看:115
本文介绍了格式.NET DateTime“Day”没有前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码,我希望结果等于2,因为MSDN表示'd'表示从1到31的数字的一个月中的日期。单位数一天的格式没有前导零。

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

但是,结果实际上等于'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");

MSDN

这篇关于格式.NET DateTime“Day”没有前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆