3

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:00}:{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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Narazana
  • 33
  • 1
  • 3

1 Answers1

6

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!

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Even though the initial poster asked for it, I think there's a bug in this response. Because totalHours contains partial hours as a fraction, the 00 format will ROUND UP and display "1 hr 37 mn" for a timeSpan of just 37 minutes. So I believe there should be an Math.Truncate() around theTimeSpan.TotalHours. If I'm right, then Jon Skeet should give me a bounty; he's got plenty to spare. :) – Knox Aug 03 '10 at 19:07