c# - 很好地显示时间跨度

标签 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;
}

最佳答案

类似:

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;
}

关于c# - 很好地显示时间跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9292014/

相关文章:

c# - 处理 worker 线程错误和结果?

javascript - 通过 JavaScript AJAX GET 将参数传递给 MVC Controller

c# - 错误 : Non-invocable member 'Vector2' cannot be used like a method

c# - BitVector32的CreateMask函数有什么作用?

formatting - 直播功能 - ExpressionEngine

c# - 当每个对象的根节点使用它的 ID 命名时,使用 YamlDotNet 反序列化 YAML?

c# - 如何在不对 html 进行硬编码的情况下创建 html 报告?

.net - 附件文件名超过 13 个字符时无法正确编码/解码

html - HTML/CSS 的间距问题。为什么会发生这种情况,我该如何解决?

java - 格式化带前导符号的数字