Custom Formatters for Timestamps

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:

today.TotalDuration.ToString("hh:mm")

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:

today.TotalDuration.ToString("hh\\:mm")

or

today.TotalDuration.ToString(@"hh\:mm")

Hopefully this will help someone that runs into this potentially frustrating problem!

Leave a Reply

Your email address will not be published. Required fields are marked *