HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpModerate

Format a timespan with up to two fields

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formatwithfieldstwotimespan

Problem

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.)

Currently my code is below, but I'm wondering if there might be a shorter way to format the timespan in this manner? I'm not fully sure if String.Format will work…

public string FormatRushTime ( System.TimeSpan span )
{
    string t1;
    string t2;
    if ( span.Days > 0 )
    {
        t1 = span.ToString("%d") + "d";
        t2 = span.Hours > 0 ? span.ToString("%h") + "h" : String.Empty;
    }
    else if ( span.Hours > 0 )
    {
        t1 = span.ToString("%h") + "h";
        t2 = span.Minutes > 0 ? span.ToString("%m") + "m" : String.Empty;
    }
    else if ( span.Minutes > 0 )
    {
        t1 = span.ToString("%m") + "m";
        t2 = span.Seconds > 0 ? span.ToString("%s") + "s" : String.Empty;
    }
    else if ( span.Seconds > 0 )
    {
        t1 = span.ToString("%s") + "s";
        t2 = String.Empty;
    }
    else
    {
        t1 = String.Empty;
        t2 = String.Empty;
    }

    return t1+" "+t2;
}

Solution

What you want to do, is use early-returns (FTW). Also, let the formatter do the string work for you. Right tool for the job.

Consider your code, rewritten in Ideone...:

static string FormatRushTime (TimeSpan span)
{
    if ( span.Days != 0 )
    {
        return String.Format("{0:d}d {1:d}h", span.Days, Math.Abs(span.Hours));
    }
    if ( span.Hours != 0 )
    {
        return String.Format("{0:d}h {1:d}m", span.Hours, Math.Abs(span.Minutes));
    }
    if ( span.Minutes != 0 )
    {
        return String.Format("{0:d}m {1:d}s", span.Minutes, Math.Abs(span.Seconds));
    }
    return String.Format("{0:d}s", span.Seconds);
}

Code Snippets

static string FormatRushTime (TimeSpan span)
{
    if ( span.Days != 0 )
    {
        return String.Format("{0:d}d {1:d}h", span.Days, Math.Abs(span.Hours));
    }
    if ( span.Hours != 0 )
    {
        return String.Format("{0:d}h {1:d}m", span.Hours, Math.Abs(span.Minutes));
    }
    if ( span.Minutes != 0 )
    {
        return String.Format("{0:d}m {1:d}s", span.Minutes, Math.Abs(span.Seconds));
    }
    return String.Format("{0:d}s", span.Seconds);
}

Context

StackExchange Code Review Q#52622, answer score: 15

Revisions (0)

No revisions yet.