2

I have a problem with 'd' specifier in DateTime format string. MSDN says:

The "d" custom format specifier represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero.

If I use this format specifier with other symbols in format string the result will be correct:

DateTime date1 = new DateTime(2008, 1, 2, 6, 30, 15);
Console.WriteLine(date1.ToString("d ")); //with space after 'd'
//displays: 2 

but if I remove space from this sample

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

the result becomes to "1/2/2008".

Why result string depends on format string length? And how can I avoid this?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Kirill
  • 7,580
  • 6
  • 44
  • 95

2 Answers2

7

Because as a single character, it behaves as The "d" standard format specifier which returns ShortDatePattern of the CurrentCulture (looks like it is M/d/yyyy for your settings) but with space, it behaves as The "d" custom format specifier which returns day numbers without leading zero for single digit days.

From The "d" Custom Format Specifier

If the "d" format specifier is used without other custom format specifiers, it is interpreted as The "d" standard date and time format specifier. For more information about using a single format specifier, see Using Single Custom Format Specifiers later in this topic.

And from Using Single Custom Format Specifiers

A custom date and time format string consists of two or more characters. Date and time formatting methods interpret any single-character string as a standard date and time format string. If they do not recognize the character as a valid format specifier, they throw a FormatException. For example, a format string that consists only of the specifier "h" is interpreted as a standard date and time format string. However, in this particular case, an exception is thrown because there is no "h" standard date and time format specifier.

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.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

well you can avoid this issue using the Day properties in the DateTime class

Console.WriteLine(date1.Day.ToString());
Popoi Menenet
  • 1,018
  • 9
  • 20