Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan ToString "[d.]hh:mm"

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");
like image 440
riofly Avatar asked Sep 22 '12 11:09

riofly


2 Answers

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();
like image 169
Tim S. Avatar answered Sep 22 '22 17:09

Tim S.


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.

like image 30
akton Avatar answered Sep 18 '22 17:09

akton