TimeSpan FormatString with optional hours
I 开发者_StackOverflow社区have a timespan, ts
, that has mostly minutes and seconds, but sometimes hours.
I'd like ts
to return a formatted string that'll give the following results:
3:30 (hours not displayed, showing only full minutes)
13:30
1:13:30 (shows only full hours instead of 01:13:30)
So far I have:
string TimeSpanText = string.Format("{0:h\\:mm\\:ss}", MyTimeSpan);
but it's not giving the above results. How can I achieve the results I want?
Maybe you want something like
string TimeSpanText = string.Format(
MyTimeSpan.TotalHours >= 1 ? @"{0:h\:mm\:ss}" : @"{0:mm\:ss}",
MyTimeSpan);
I don't think a single format string will give you what you want, but building the output yourself is a simple task:
public string FormatTimeSpan(TimeSpan ts)
{
var sb = new StringBuilder();
if ((int) ts.TotalHours > 0)
{
sb.Append((int) ts.TotalHours);
sb.Append(":");
}
sb.Append(ts.Minutes.ToString("m"));
sb.Append(":");
sb.Append(ts.Seconds.ToString("ss"));
return sb.ToString();
}
EDIT: Better idea!
You could make the method above an extension method on the TimeSpan
class like so:
public static class Extensions
{
public static string ToMyFormat(this TimeSpan ts)
{
// Code as above.
}
}
Then using this is as simple as invoking ts.ToMyFormat()
.
精彩评论