2010-01-13 111 views
3

我要格式化的时间跨度为具有这样的49小时格式34个MN 20秒Custome格式时间跨度与的String.Format

我用下面的字符串格式:

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

它格式化入库时间到这种格式49:34:20。我如何将hr mn sec添加到上面的String.Format中?或者有另一种简单的方法?谢谢。

回答

6

这很简单:

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

+0

感谢您的答案和信息。 :D – Narazana 2010-01-13 17:10:15

+1

尽管最初的海报要求提供,但我认为这种回应存在一个错误。由于totalHours包含部分小时数作为分数,因此00格式将ROUND UP并显示“1小时37分钟”,时间跨度仅为37分钟。所以我相信在TimeSpan.TotalHours周围应该有一个Math.Truncate()。如果我是对的,那么Jon Skeet应该给我一笔赏金;他有足够的空间。 :) – Knox 2010-08-03 19:07:15

+0

好斑。定影。 – 2010-08-03 19:08:53