I came across a particularly aggravating problem today while using a custom Timespan formatter inside the ToString() method override: “Input string was not in a correct format.”
The call in question was:
[csharp]
today.TotalDuration.ToString(“hh:mm”)
[/csharp]
So why doesn’t that work? Well if you go to the MSDN page for Custom TimeSpan Format Strings here, you will notice a yellow box at the top of the screen stating that the “TimeSpan format specifiers do not include placeholder seperator symbols”, meaning that we have to put in a backslash to escape the literal we want put in. The string that the ToString override wants is: hh\:mm to display hours and minutes like this: 03:51
The Solution
Escape your colon or other literal characters by using code like this:
[csharp]
today.TotalDuration.ToString(“hh\\:mm”)
[/csharp]
or
[csharp]
today.TotalDuration.ToString(@”hh\:mm”)
[/csharp]
Hopefully this will help someone that runs into this potentially frustrating problem!