是否有更简单的方法来格式化这个时间跨度?

时间:2014-06-06 13:48:04

标签: .net time

我希望获得一个如下所示的时间格式: 2d 4h ;或者 1h 36m ;或者 35s 等等。这样它只显示两个最大的时间值(这就是Clash of Clans和其他一些手机游戏格式的等待时间。)

目前我的代码如下,但我想知道是否可能有更短的方式以这种方式格式化时间跨度?我不完全确定String.Format是否有效......

static function FormatRushTime ( span : System.TimeSpan )
{
    if ( span.Days > 0 )
    {
        var t1 = span.ToString("%d") + "d";
        var t2 = span.Hours > 0 ? ToString("%h") + "h" : String.Empty;
    }
    else if ( span.Hours > 0 )
    {
        t1 = span.ToString("%h") + "h";
        t2 = span.Minutes > 0 ? ToString("%m") + "m" : String.Empty;
    }
    else if ( span.Minutes > 0 )
    {
        t1 = span.ToString("%m") + "m";
        t2 = span.Seconds > 0 ? 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;
}

2 个答案:

答案 0 :(得分:1)

您可以使用Humanizer之类的外部库。或者,如果你想要一个肮脏的解决方案,你总是可以连接组件......

     TimeSpan rawr = new TimeSpan(0, 1, 1, 1);
     string rawrString = "";

     rawrString += rawr.Days > 0 ? String.Format("{0:%d}d ", rawr) : "";
     rawrString += rawr.Hours > 0 ? String.Format("{0:%h}h ", rawr) : "";
     rawrString += rawr.Minutes > 0 ? String.Format("{0:%m}m ", rawr) : "";
     rawrString += rawr.Seconds > 0 ? String.Format("{0:%s}s ", rawr) : "";

为了只获得两个时间组件,您可以添加一个计数器:

     TimeSpan rawr = new TimeSpan(1, 1, 1, 1);
     string rawrString = "";
     int TimeComponentCounter = 0;

     rawrString += rawr.Days > 0 ? String.Format("{0:%d}d ", rawr) : "";
     if (rawrString.Contains("d")) TimeComponentCounter++;
     if (TimeComponentCounter < 2) rawrString += rawr.Hours > 0 ? String.Format("{0:%h}h ", rawr) : "";
     if (rawrString.Contains("h")) TimeComponentCounter++;
     if (TimeComponentCounter < 2) rawrString += rawr.Minutes > 0 ? String.Format("{0:%m}m ", rawr) : "";
     if (rawrString.Contains("m")) TimeComponentCounter++;
     if (TimeComponentCounter < 2) rawrString += rawr.Seconds > 0 ? String.Format("{0:%s}s ", rawr) : "";

答案 1 :(得分:0)

在codereview.stackexchange.com上通过@rolfl的简单方法:

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