使用标准或自定义日期格式

Using standard or custom date formats

以下代码:

DateTime test = new DateTime();
Console.WriteLine(test.ToString("d"));
Console.WriteLine(test.ToString("d_"));
Console.WriteLine(test.ToString("dd"));

产生以下结果:

0001-01-01
1_
01

第一个结果是完整日期,因为 d 被视为标准日期格式。另一方面,d_ 被视为自定义日期格式,在这种情况下 d 被视为短日期字符串。有没有办法只生成没有下划线的短日?

其中任何一项:

Console.WriteLine(test.ToString("%d"));
Console.WriteLine(test.ToString(" d"));
Console.WriteLine(test.ToString("d "));

来自https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx#UsingSingleSpecifiers

To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.

恐怕这个问题只有解决方法。你想被 date.ToString("d") 解释为 custom date time format string which shows the day. But per definition a single format specifier always specifies a standard date and time format string.

你可以直接使用DateTime.Day:

Console.WriteLine(test.Day);

或使用 d 和空 space + Trim 的技巧:

Console.WriteLine(test.ToString(" d ").Trim());

MSDN:

A standard date and time format string uses a single format specifier to define the text representation of a date and time value. Any date and time format string that contains more than one character, including white space, is interpreted as a custom date and time format string

根据 msdn 你可以这样做:

Console.WriteLine(test.ToString("%d"));