Link to home
Start Free TrialLog in
Avatar of indy500fan
indy500fan

asked on

How do I format a string, from a timespan, to have 2 digits (i.e. 2 should be 02)

Friends,

I need help with "padding a string", with a leading 0 for seconds < 10.

I get my seconds String from this:
Dim Seconds As String = GetSeconds(CurrentQualifierTotalTime)

  Public Function GetSeconds(ByVal ElapsedSessionTime As Decimal)
        Dim ts As TimeSpan
        ts = TimeSpan.FromSeconds(ElapsedSessionTime)
        Return ts.Seconds
    End Function
Then I tried without success the following:

Seconds = String.Format(Seconds, "#0")

Thanks in advance!
ASKER CERTIFIED SOLUTION
Avatar of PaulHews
PaulHews
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of indy500fan
indy500fan

ASKER

Paul,

Nope same result.
Make sure you return the right type...  This shows a message box with 03, so it works.
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MsgBox(GetSeconds(3).ToString("00"))
    End Sub
 
 
    Public Function GetSeconds(ByVal ElapsedSessionTime As Decimal) As Integer
        Dim ts As TimeSpan
        ts = TimeSpan.FromSeconds(ElapsedSessionTime)
        Return ts.Seconds
    End Function

Open in new window

Well Sure enough, when I do it in another NEW project, your method works; however, it won't work in my current solution.  Any suggestions?
Look here, watching the variable, at a breakpoint, it shows 2, not 02.
Seconds.JPG
Did you fix the GetSeconds function to return an integer?  In your original code, you did not specify a return type.... (One reason I always use Option Strict On...)
Yep, this makes the difference...

    Public Function GetSeconds(ByVal ElapsedSessionTime As Decimal) As Integer
        Dim ts As TimeSpan
        ts = TimeSpan.FromSeconds(ElapsedSessionTime)
        Return ts.Seconds
    End Function
And it does!  Thank you!