开发者

Custom format Timespan with String.Format

开发者 https://www.devze.com 2022-12-16 12:11 出处:网络
I want to format the Timespan to have format like this 49 hr 34 mn 20 sec I used the String format below:

I want to format the Timespan to have format like this 49 hr 34 mn 20 sec

I used the String format below:

String.Format("{0:00}:{1:0开发者_JAVA技巧0}:{2:00}", theTimeSpan.TotalHours, theTimeSpan.Minutes, theTimeSpan.Seconds)

It formats the Timespan to this format 49:34:20. How can I add hr mn sec to the String.Format above? or there's another easy way? Thank you.


That's simple:

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

It's worth becoming familiar with how string formatting works in .NET - it's an important topic.

It's unfortunate that TimeSpan doesn't support custom format strings at the moment - but it will as of .NET 4.0!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号