Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do these two date formats differ?

I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the docs, 'd' should produce the day (1-31).

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

UPDATE:Adding % is indeed the trick. Appropriate docs here.

like image 869
lesscode Avatar asked Aug 05 '26 16:08

lesscode


2 Answers

See here

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.

Otherwise d is interpreted as:

d - 'ShortDatePattern'

PS. For messing around with format strings, using LinqPad is invaluable.

like image 151
Robert Paulson Avatar answered Aug 08 '26 12:08

Robert Paulson


From the MSDN documentation for "Custom Date and Time Format Strings":

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

{0:d} is interpreted as a standard data and time format string. From "Standard Date and Time Format Strings", the "d" format specifier:

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

With the space, {0:d } doesn't match any standard date and time format string, and is interpreted as a custom data and time format string. From "Custom Date and Time Format Strings", the "d" format specifier:

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

like image 38
Michael Petrotta Avatar answered Aug 08 '26 10:08

Michael Petrotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!