How to Format the TimeSpan Property in VB.Net
The VB.Net TimeSpan object represents a time interval, either time elapsed in the past, a current duration of time or a duration of time yet to come. TimeSpan can be employed in a wide variety of constructions, including data entry, calculations, generation and modulation of reports, and any other number of front or back end applications. TimeSpan accepts a large number of properties, methods, and operators, and can specify days, hours, minutes, seconds, and even milliseconds.
Instructions
-
-
1
To initiate a set of specified TimeSpan values, a variable needs to be declared as a new TimeSpan() object. For example: "Dim tsElapsed As New TimeSpan(2,30,0)." TimeSpan() accepts one constructor variable, such as TimeSpan(Int64), for ticks; three variables, such as TimeSpan(Int32, Int32, Int32), for hours, minutes, and seconds; four variables, TimeSpan(Int32, Int32, Int32, Int32), for days, hours, minutes, and seconds, and five variables, TimeSpan(Int32, Int32, Int32, Int32, Int32), for days, hours, minutes, seconds, and milliseconds. Our example above, TimeSpan(2,30,0), when converted and called, would display a span of 2 hours, 30 minutes, and 0 seconds.
-
2
Although TimeSpan() can be converted and utilized in a wide variety of ways, the simplest method for displaying its values with minimal formatting is the ToString method. Simply declare a new variable as a string and set its value to that of the TimeSpan(). Example: "Dim strElapsed As String = tsElapsed." When the string is called or assigned to a front end object, it will display as DD.HH:mm:ss:ms, according to how many constructor variables are used.
-
-
3
However, if one wants to have more specified formatting in their TimeSpan(), its values will have to be converted to a DateTime(). To do this, declare a new DateTime() with the assigned TimeSpan() including its constructors called. For example: "Dim dtElapsed As New DateTime(tsElapsed.Ticks)." The newly set DateTime() can either be formatted according to standard DateTime() methods, such as LongDate or ShortDate, or, because DateTime is more flexible in its conversions, it can be converted to a String and formatted subsequently.
-
1
Tips & Warnings
Depending on your application, you may want to experiment with different conversion and call methods to produce the most efficacious result from your TimeSpan().
References
Resources
- Photo Credit Jupiterimages/Photos.com/Getty Images