Typing in the title to this question brought me to this question. I\'m looking for the same thing, but something perhaps less statically formatted if you get what I mean?
And if you care about pluralization:
public static string ToPrettyFormat(this TimeSpan span) {
if (span == TimeSpan.Zero) return "0 minutes";
var sb = new StringBuilder();
if (span.Days > 0)
sb.AppendFormat("{0} day{1} ", span.Days, span.Days > 1 ? "s" : String.Empty);
if (span.Hours > 0)
sb.AppendFormat("{0} hour{1} ", span.Hours, span.Hours > 1 ? "s" : String.Empty);
if (span.Minutes > 0)
sb.AppendFormat("{0} minute{1} ", span.Minutes, span.Minutes > 1 ? "s" : String.Empty);
return sb.ToString();
}
You can just output this directly:
string result = string.Format("{0} days, {1} hours, {2} minutes", duration.Days, duration.Hours, duration.Minutes);
If you are going to be handling "short" times, and you want this to be cleaner, you could do something like:
public string PrettyFormatTimeSpan(TimeSpan span)
{
if (span.Days > 0)
return string.Format("{0} days, {1} hours, {2} minutes", span.Days, span.Hours, span.Minutes);
if (span.Hours > 0)
return string.Format("{0} hours, {1} minutes", span.Hours, span.Minutes);
return string.Format("{0} minutes", span.Minutes);
}
With C# 7:
string FormatTimeSpan(TimeSpan timeSpan)
{
string FormatPart(int quantity, string name) => quantity > 0 ? $"{quantity} {name}{(quantity > 1 ? "s" : "")}" : null;
return string.Join(", ", new[] { FormatPart(timeSpan.Days, "day"), FormatPart(timeSpan.Hours, "hour"), FormatPart(timeSpan.Minutes, "minute") }.Where(x => x != null));
}