-1

I am trying to format a TimeSpan with the following line of code:

.ToString("[d.]hh:mm:ss")

It throws a FormatException, but the exception goes away when I remove the :, the [], and the .. I also cannot include spaces. Does anyone know why this is happening? On this msdn page it clearly states that you can include these characters. I am using .Net framework 4.5.2 btw.

Thanks.

TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101
  • These characters have to be [escaped](http://msdn.microsoft.com/en-us/library/ee372287%28v=vs.110%29.aspx#Other). By the way, do you really want square brackets around `d.` or are they only the result of copy-pasting the format string from MSDN? – Frédéric Hamidi Jun 20 '14 at 13:33
  • I assumed the `[]` would mean that nothing inside them would render had the `d` element not been shown; I don't want a stranded `.`. There was nothing on the MSDN about escaping, plus I tried adding a `@` in front of the string and it still didn't work. – TheGateKeeper Jun 20 '14 at 13:35
  • 1
    @TheGateKeeper That's not how you escape a character, that's a string literal. – tnw Jun 20 '14 at 13:38
  • I thought it automatically escaped all of the characters inside the string. – TheGateKeeper Jun 20 '14 at 13:39

2 Answers2

1
TimeSpan ts = new TimeSpan(5, 10, 44);
string test = string.Format("{0:dd\\:hh\\:mm\\:ss\\.ffff}", ts);
Kevin Cook
  • 1,922
  • 1
  • 15
  • 16
1

You need to escape the literal characters. It's quite awkward but this is what you need.

TimeSpan ts = new TimeSpan(1, 2, 3, 4, 555);

string output = ts.ToString("d\\.hh\\:mm\\:ss");

See Docs here.

Patrick Allwood
  • 1,822
  • 17
  • 21