TimeSpan ToString "[d.]hh:mm"

riofly picture riofly · Sep 22, 2012 · Viewed 9.8k times · Source

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");

Answer

Tim S. picture Tim S. · Sep 22, 2012

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();