【问题标题】:Custom format Timespan with String.Format使用 String.Format 自定义格式时间跨度
【发布时间】:2010-01-13 17:04:04
【问题描述】:

我想将时间跨度格式化为 49 小时 34 百万 20 秒这样的格式

我使用了下面的字符串格式:

String.Format("{0:00}:{1:00}:{2:00}", theTimeSpan.TotalHours, theTimeSpan.Minutes, theTimeSpan.Seconds)

它将时间跨度格式化为这种格式 49:34:20。如何将 hr mn sec 添加到上面的 String.Format 中?还是有另一种简单的方法?谢谢。

【问题讨论】:

    标签: vb.net timespan


    【解决方案1】:

    这很简单:

    String.Format("{0:00} hr {1:00} mn {2:00} sec ", _
                  Math.Truncate(theTimeSpan.TotalHours), _
                  theTimeSpan.Minutes, theTimeSpan.Seconds)
    

    值得熟悉how string formatting works in .NET - 这是一个重要的话题。

    很遗憾TimeSpan 目前不支持自定义格式字符串 - but it will as of .NET 4.0

    【讨论】:

    • 感谢您的回答和信息。 :D
    • 尽管最初的发帖人要求这样做,但我认为此响应存在错误。因为 totalHours 包含部分小时作为分数,00 格式将向上取整并显示“1 小时 37 分钟”,时间跨度仅为 37 分钟。所以我相信 TimeSpan.TotalHours 周围应该有一个 Math.Truncate()。如果我是对的,那么 Jon Skeet 应该给我一个赏金;他有足够的余地。 :)
    猜你喜欢
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多