We help IT Professionals succeed at work.

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

on
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")

Comment
Watch Question

## View Solution Only

Commented:
Dim Seconds As String = GetSeconds(CurrentQualifierTotalTime).ToString("00")

Commented:
Paul,

Nope same result.

Commented:
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
``````

Commented:
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?

Commented:
Look here, watching the variable, at a breakpoint, it shows 2, not 02.
Seconds.JPG

Commented:
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...)

Commented:
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

Commented:
And it does!  Thank you!