Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleFormat a TimeSpan in days, hours, minutes, and seconds in VB.NET
DescriptionThis example shows how to format a TimeSpan in days, hours, minutes, and seconds in VB.NET.
KeywordsTimeSpan, VB.NET, format
CategoriesStrings, VB.NET
 
The FormatTimeSpan function returns a string representing a TimeSpan. It uses the Days, Hours, Minutes, and Seconds to pull out the different increments of time and adds them to its string.
 
Private Function FormatTimeSpan(ByVal time_span As _
    TimeSpan, Optional ByVal whole_seconds As Boolean = _
    True) As String
    Dim txt As String = ""

    If time_span.Days > 0 Then
        txt &= ", " & time_span.Days.ToString() & " days"
        time_span = time_span.Subtract(New _
            TimeSpan(time_span.Days, 0, 0, 0))
    End If
    If time_span.Hours > 0 Then
        txt &= ", " & time_span.Hours.ToString() & " hours"
        time_span = time_span.Subtract(New TimeSpan(0, _
            time_span.Hours, 0, 0))
    End If
    If time_span.Minutes > 0 Then
        txt &= ", " & time_span.Minutes.ToString() & " " & _
            "minutes"
        time_span = time_span.Subtract(New TimeSpan(0, 0, _
            time_span.Minutes, 0))
    End If

    If whole_seconds Then
        ' Display only whole seconds.
        If time_span.Seconds > 0 Then
            txt &= ", " & time_span.Seconds.ToString() & " " & _
                "seconds"
        End If
    Else
        ' Display fractional seconds.
        txt &= ", " & time_span.TotalSeconds.ToString() & " " & _
            "seconds"
    End If

    ' Remove the leading ", ".
    If txt.Length > 0 Then txt = txt.Substring(2)

    ' Return the result.
    Return txt
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated