I'm looking to achieve a time format that looks like this: 2d 4h remaining; or 1h 36m remaining; or 35s remaining, etc. So that it only displays the two largest values of time (this is how Clash of Clans and some other mobile games format wait times.)
I would like to format the wait time value as simply 5h or 5h 0m depending on whether I am displaying the total wait time or currently counting down. My code is below… But is there a slightly simpler way of writing it without so many returns?
(This question was originally asked here: Is there a simpler way to format this timespan? )
public string FormatRushTime ( System.TimeSpan span, boolean removeZeros )
{
if ( span.Days > 0 )
{
if ( span.Hours > 0 || !removeZeros )
return String.Format("{0:d}d {1:d}h", span.Days, span.Hours);
else
return String.Format("{0:d}d", span.Days);
}
if ( span.Hours > 0 )
{
if ( span.Minutes > 0 || !removeZeros )
return String.Format("{0:h}h {1:m}m", span.Hours, span.Minutes);
else
return String.Format("{0:h}h", span.Hours);
}
if ( span.Minutes > 0 )
{
if ( span.Seconds > 0 || !removeZeros )
return String.Format("{0:m}m {1:s}s", span.Minutes, span.Seconds);
else
return String.Format("{0:m}m", span.Minutes);
}
return String.Format("{0:d}s", span.Seconds);
}