views:

243

answers:

3

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.

+5  A: 

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.

Robert Paulson
Thanks -- '%' does the trick. Appropriate doc section at http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers.
Wayne
+1  A: 

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.

Michael Petrotta
A: 

The {0:d} format uses the patterns defined in the Standard Date and Time Format Strings document of MSDN. 'd' translates to the short date pattern, 'D' to the long date pattern, and so on and so forth.

The format that you want appears to be the Custom Date and Time Format Modifiers, which work when there is no matching specified format (e.g., 'd ' including the space) or when you use ToString().

You could use the following code instead:

string.Format("{0}", DateTime.Today.ToString("d ", CultureInfo.InvariantCulture));
Jon Limjap
Also includes a redundant space.
Wayne