DateTime ToString 坏了?

DateTime ToString broken?

为了

DateTime aDate = new DateTime(2000,1,1);  
Console.WriteLine(aDate.ToString("d"));

我期望 1,但它写 1/1/2000

MSDN 说:

d 一个月中的第几天,从 1 到 31。

2009-06-01T13:45:30 -> 1

2009-06-15T13:45:30 -> 15

有什么解决办法吗? M.

也一样

dotnetfiddle

来自docs

If the "d" format specifier is used without other custom format specifiers, it's interpreted as the "d" standard date and time format specifier.

“d”是 The Short Date ("d") Format Specifier

如果您只需要一个月中的某一天,则 DateTime.Day:

Console.WriteLine(aDate.Day);

或者,您可以在格式字符串前加上 %:

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

您已经创建了 DateTime 对象,因此您可以从 aDate.Day 或 aDate.Month 访问它的属性,如果您想从 datetime 对象中获取日期 属性,只需

Console.WriteLine(aDate.Days.ToString()); // in your case

您的方向正确。要仅打印日期,您必须改写:

Console.WriteLine(aDate.ToString("dd"));

月份应该是:

Console.WriteLine(aDate.ToString("MM"));

解决方案是:

Console.WriteLine(aDate.ToString(" d"));

: 和 d 之间的 space 很重要。 M也一样。