C# 格式化 .NET DateTime“Day”,没有前导零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/988353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:00:02  来源:igfitidea点击:

Format .NET DateTime "Day" with no leading zero

c#datetimeformatting

提问by Marcel Lamothe

For the following code, I would expect resultto 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.".

对于下面的代码,我希望结果等于 2,因为 MSDN 声明 'd'“将月份中的日期表示为 1 到 31 之间的数字。一位数的日期格式不带前导零。”。

DateTime myDate = new DateTime( 2009, 6, 4 );
string result = myDate.ToString( "d" );

However, resultis 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.

但是,结果实际上等于 '6/4/2009' - 这是短日期格式(也是 'd')。我可以使用“dd”,但这会增加一个前导零,这是我不想要的。

采纳答案by Marcel Lamothe

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

See documentation

查看文档

回答by James Conigliaro

Rather than using string formatting strings, how about using the Day property

不使用字符串格式化字符串,如何使用 Day 属性

DateTime myDate = new DateTime(2009,6,4)
int result = myDate.Day;

Or if you really needed the result in string format

或者如果你真的需要字符串格式的结果

string result = myDate.Day.ToString();

If you are looking to get a specific date part out of a date object rather than a formatted representation of the date, I prefer to use the properties (Day, Month, Year, DayOfWeek, etc.) It makes reading the code a bit easier (particularly if someone else is reading/maintaining it that doesn't have the various formatting codes memorized)

如果您希望从日期对象中获取特定日期部分而不是日期的格式化表示,我更喜欢使用属性(日、月、年、DayOfWeek 等)。它使阅读代码更容易一些(特别是如果其他人正在阅读/维护它而没有记住各种格式代码)