none
How to format a timespan?

    Question

  •        

    Trying to calculate and format for text a brief timespan of minutes, seconds, and maybe milliseconds

            Dim diff As TimeSpan
            diff = DateTime.Now - StartTime

    Tried several things I found online, here are a couple:

            lblTime.Text = "Elapsed time = " & String.Format("HH:MM:ss", diff)

           lblTime.Text = "Elapsed time = " & diff.TotalSeconds.ToString("HH:MM:ss")  

    Not working so far.  I get

    Elapsed time = HH:MM:ss

    Thanks

    Thursday, September 06, 2012 12:09 AM

Answers

All replies

  • Look at the properties of TimeSpan - specifically .Hours and .Minutes, etc.

    Please call me Frank :)

    Thursday, September 06, 2012 12:13 AM
  • this worked

       lblTime.Text = "Elapsed time = " & diff.ToString("mm':'ss")

    Thursday, September 06, 2012 12:16 AM
  • TotalSeconds is the number of seconds - not a timespan.

    If you need to format as hours, minutes & seconds, you can do something similar to the following:

    Dim secs = diff.TotalSeconds
    Dim hours = secs \ 3600
    Dim minutes = (secs - hours*3600) \ 60
    Dim seconds = secs - hours*3600 - minutes*60
    
    lblTime.Text = String.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds)

    Please note that the code above is untested - just wanted to show you the idea.

    Alternatively, I suspect that the TimeSpan should support the ToString(format) overload, so that the above may be simplified to just:

    lblTime.Text = diff.ToString("HH:MM:ss")

    Thursday, September 06, 2012 12:19 AM