很好地显示时间跨度

时间:2012-02-15 10:55:04

标签: c# .net formatting timespan

请原谅粗略的代码,我试图以秒为单位显示视频的持续时间。  我已经过了一段时间,但它运作不正常。

我希望它能很好地显示 - 即显示9m:59s而不是09m:59s。

如果小时数为零则不显示小时数,如果小时数为零则不显示分钟数。

public static string GetTimeSpan(int secs)
{
    TimeSpan t = TimeSpan.FromSeconds(secs);

    string answer;
    if (secs < 60)
    {
        answer = string.Format("{0:D2}s", t.Seconds);
    }
    else if (secs < 600)//tenmins
    {
        answer = string.Format("{0:m}m:{1:D2}s", t.Minutes, t.Seconds);

    }
    else if (secs < 3600)//hour
    {
        answer = string.Format("{0:mm}m:{1:D2}s", t.Minutes, t.Seconds);
    }
    else
    {
        answer = string.Format("{0:h}h:{1:D2}m:{2:D2}s",
                                    t.Hours,
                                    t.Minutes,
                                    t.Seconds);
    }

    return answer;
}

4 个答案:

答案 0 :(得分:25)

类似的东西:

public static string PrintTimeSpan(int secs)
{
   TimeSpan t = TimeSpan.FromSeconds(secs);
   string answer;
   if (t.TotalMinutes < 1.0)
   {
     answer = String.Format("{0}s", t.Seconds);
   }
   else if (t.TotalHours < 1.0)
   {
     answer = String.Format("{0}m:{1:D2}s", t.Minutes, t.Seconds);
   }
   else // more than 1 hour
   {
     answer = String.Format("{0}h:{1:D2}m:{2:D2}s", (int)t.TotalHours, t.Minutes, t.Seconds);
   }

   return answer;
}

答案 1 :(得分:3)

我认为您可以通过移除&#34; D2&#34;来简化这一过程。格式方面,然后你不需要一个特殊情况下十分钟的选项。基本上只是使用

string.Format("{0}m:{1}s", t.Minutes, t.Seconds);

会根据需要为您提供一位或两位数字。所以你的最后一个案例是:

string.Format("{0}h:{1}m:{2}s", t.Hours, t.Minutes, t.Seconds);

答案 2 :(得分:2)

根据msdn试试这个:

if (secs < 60)
{
    answer = t.Format("s");
}
else if (secs < 600)//tenmins
{
    answer = t.Format("m:s");
}
// ...

答案 3 :(得分:1)

readonly static Char[] _colon_zero = { ':', '0' };
// ...

var ts = new TimeSpan(DateTime.Now.Ticks);
String s = ts.ToString("h\\:mm\\:ss\\.ffff").TrimStart(_colon_zero);
.0321
6.0159
19.4833
8:22.0010
1:04:2394
19:54:03.4883