11

I trying to format a TimeSpan to string. Then I get expiration from MSDN to generate my customized string format. But it don't words. It returns "FormatException".

Why? I don't understand...

var ts = new TimeSpan(0, 3, 25, 0);
var myString = ts.ToString("[d'.']hh':'mm");
riofly
  • 1,694
  • 3
  • 19
  • 40

2 Answers2

14

I take it you're trying to do something like the optional day and fractional seconds portions of the c standard format. As far as I can tell, this isn't directly possible with custom format strings. TimeSpan FormatString with optional hours is the same sort of question you have, and I'd suggest something similar to their solution: have an extension method build the format string for you.

public static string ToMyFormat(this TimeSpan ts)
{
    string format = ts.Days >= 1 ? "d'.'hh':'mm" : "hh':'mm";
    return ts.ToString(format);
}

Then to use it:

var myString = ts.ToMyFormat();
Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • Yes, it will works for sure. But I would use ToString format. MSDN says that I can use "[" and "]". Is it true? – riofly Sep 22 '12 at 13:21
  • 1
    Where does it say that? The only times I noticed `[` and `]` was how it describes the standard format strings, but without saying you can actually use those 'magic' symbols in custom formats. – Tim S. Sep 22 '12 at 14:06
  • It says so on this page (https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-timespan-format-strings) in the first table. – Robert Massa Sep 06 '22 at 21:05
3

This error usually occurs when you use symbols that have defined meanings in the format string. The best way to debug these is selectively remove characters until it works. The last character you removed was the problem one.

In this case, looking at the custom TimeSpan format strings, the square brackets are the problem. Escape them with "\", for example:

var ts = new TimeSpan(0, 3, 25, 0);
var myString = ts.ToString("\\[d'.'\\]hh':'mm");

[Edit: Added]

There is no way mentioned on the customer custom TimeSpan format strings page to omit text if values are 0. In this case, consider an if statement or the ?: operator.

akton
  • 14,148
  • 3
  • 43
  • 47
  • Yes, I know that the square brackets are the problem. But I look that I can use "[" and "]" to returns days only when the value is >= 0. Is it possible? – riofly Sep 22 '12 at 13:16
  • @riofly There does not appear to be any way to omit a portion of the string if a value is 0 in http://msdn.microsoft.com/en-us/library/ee372287.aspx. Perhaps ah if statement is better. Answer is updated. – akton Sep 22 '12 at 13:24