TimeSpan ToString "[d.]hh:mm"
Asked Answered
B

2

12

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");
Burdelle answered 22/9, 2012 at 11:33 Comment(0)
H
15

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();
Headrest answered 22/9, 2012 at 11:49 Comment(3)
Yes, it will works for sure. But I would use ToString format. MSDN says that I can use "[" and "]". Is it true?Burdelle
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.Headrest
It says so on this page (learn.microsoft.com/en-us/dotnet/standard/base-types/…) in the first table.Allx
P
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.

Psoas answered 22/9, 2012 at 11:38 Comment(2)
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?Burdelle
@Burdelle There does not appear to be any way to omit a portion of the string if a value is 0 in msdn.microsoft.com/en-us/library/ee372287.aspx. Perhaps ah if statement is better. Answer is updated.Psoas

© 2022 - 2024 — McMap. All rights reserved.