Format .NET DateTime quot;Dayquot; with no leading zero(格式化 .NET DateTime“日;没有前导零)
问题描述
对于以下代码,我希望 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“日";没有前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:格式化 .NET DateTime“日";没有前导零
基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
