为什么这两种日期格式不同?

时间:2020-03-06 15:03:30  来源:igfitidea点击:

我试图在WPF文本块中仅生成日期数字,而没有前导零和没有多余的空格填充(这会抛出布局)。第一个产生带空格的日期,第二个产生整个日期。根据文档," d"应生成天(1-31)。

string.Format("{0:d }", DateTime.Today);
string.Format("{0:d}", DateTime.Today);

更新:添加%确实是诀窍。适当的文档在这里。

解决方案

看这里

d, %d
  
  The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns.

否则,d解释为:

d - 'ShortDatePattern'

PS。对于弄乱格式字符串,使用LinqPad是无价的。

从"自定义日期和时间格式字符串"的MSDN文档中:

Any string that is not a standard date
  and time format string is interpreted
  as a custom date and time format
  string.

{0:d}被解释为标准数据和时间格式字符串。在"标准日期和时间格式字符串"中," d"格式说明符:

Represents a custom date and time
  format string defined by the current
  ShortDatePattern property.

带有空格的{0:d}与任何标准日期和时间格式字符串都不匹配,并且被解释为自定义数据和时间格式字符串。在"自定义日期和时间格式字符串"中," d"格式说明符:

Represents the day of the month as a
  number from 1 through 31.

" {0:d}"格式使用MSDN的"标准日期和时间格式字符串"文档中定义的模式。 'd'转换为短日期模式,'D'转换为长日期模式,依此类推。

我们想要的格式似乎是"自定义日期和时间格式"修饰符,当没有匹配的指定格式(例如," d"(包括空格))或者我们使用ToString()时,它们将起作用。

我们可以改用以下代码:

string.Format("{0}", DateTime.Today.ToString("d ", CultureInfo.InvariantCulture));