1

According to MSDN, the d format specifier outputs the TimeSpan.Days property. When used in the .ToString() method this appears to be true:

TimeSpan.FromDays(1).ToString("%d")

However, when used in a String.Format, the specifier throws an exception:

String.Format("{0:d}", TimeSpan.FromDays(1))

'String.Format("{0:d}", TimeSpan.FromDays(1))' threw an exception of type 'System.FormatException'
    base {System.SystemException}: {"Input string was not in a correct format."}

The dd specifier works just fine, but gives a leading zero (as intended).

Why does the d specifier throw an exception?

Alex
  • 7,639
  • 3
  • 45
  • 58

3 Answers3

3

You are missing the %:

string.Format("{0:%d}", TimeSpan.FromDays(1))

According to the article you linked (and the example you copied):

If the "d" custom format specifier is used alone, specify "%d" so that it is not misinterpreted as a standard format string.

Joey
  • 344,408
  • 85
  • 689
  • 683
1

Typical, no sooner have I asked the question then I find the answer here - apparently this applies for both DateTime and TimeSpan (and probably every other format)

Community
  • 1
  • 1
Alex
  • 7,639
  • 3
  • 45
  • 58
0

My favorite site for String.Format is Stevex.

The line you should pay attention to is under Numbers

Specifier | Type | Format | Output (Passed Double 1.42) | Output (Passed Int -12400)
d | Decimal (Whole number) | {0:d} | System.FormatException | -12400

TimeSpan.FromDays(1) returns a double. The d formatter expects a whole number and because it receives a double, a format exception is thrown.

Josh
  • 16,286
  • 25
  • 113
  • 158