Formatting timespan objects

J

John Dann

I want to report a timespan value in a textbox on a form and thought I
might be able to do eg:

txtbox.text=format(timespan,"hh:mm:ss")

but this gives an invalid cast. Is there is any short way of achieving
this or do I need to extract and assemble each time element
separately?

Thanks
JGD
 
H

Herfried K. Wagner [MVP]

John Dann said:
I want to report a timespan value in a textbox on a form and thought I
might be able to do eg:

txtbox.text=format(timespan,"hh:mm:ss")

but this gives an invalid cast. Is there is any short way of achieving
this or do I need to extract and assemble each time element
separately?

You may want to use 'String.Format' to concatenate the property values:

\\\
MsgBox( _
String.Format( _
"{0:00}:{1:00}:{2:00}", _
ts.Hours, _
ts.Minutes, _
ts.Seconds _
) _
)
///
 
J

Jay B. Harlow [MVP - Outlook]

John,
In addition to the other comments.

The "easiest" way to format a TimeSpan is to use the TimeSpan.ToString
method, which will return the results in the format: [-][d.]hh:mm:ss[.ff]

http://msdn.microsoft.com/library/d...tml/frlrfSystemTimeSpanClassToStringTopic.asp

Dim ts As TimeSpan
txtbox.text= ts.ToString()

Remember the ToString method of "formattable" objects in .NET is normally
overridden to provide formatting for that object.

If you don't want the fractional seconds or days on the formatted string, I
normally convert the TimeSpan to a DateTime & then use custom DateTime
formatting.

Note TimeSpan itself only supports a fixed format, I will convert a TimeSpan
into a DateTime if I need custom formatting.

Dim ts As TimeSpan
Dim dt As DateTime = DateTime.MinValue.Add(ts)
Dim s As String

s = ts.ToString() ' default TimeSpan formatting
s = dt.ToString("H:mm:ss") ' custom DateTime formatting


For details on custom datetime formats see:

http://msdn.microsoft.com/library/d...s/cpguide/html/cpcondatetimeformatstrings.asp

For information on formatting in .NET in general see:
http://msdn.microsoft.com/library/d...y/en-us/cpguide/html/cpconformattingtypes.asp

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top