How to Format the TimeSpan Property in VB.Net

Written by brian kemple
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Format the TimeSpan Property in VB.Net
TimeSpan can be utilised in a wide variety of applications. (Jupiterimages/ Images)

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.

Skill level:

Other People Are Reading


  1. 1

    To initiate a set of specified TimeSpan values, a variable needs to be declared as a new TimeSpan() object. For example: "Dim ts Elapsed 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. 2

    Although TimeSpan() can be converted and utilised 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 = ts Elapsed." 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. 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.

Tips and 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().

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.