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");
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With