格式化 .NET DateTime“日";没有前导零

Format .NET DateTime quot;Dayquot; with no leading zero(格式化 .NET DateTime“日;没有前导零)
本文介绍了格式化 .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“日";没有前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)