VB.net Re-Format time string


I have an application where a user types a time value as an input such as "8:45".
I need to convert this to the format "08:45"
How do I do this?
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Anil GolamariCommented:
Dim time As DateTime = TimeOfDay

        Dim format As String = "HH:mm"



Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Thanks but I specifically asked for converting a string eg "8:45" back to a string eg "08:45"
Anil GolamariCommented:
You should be able to add a leading zero to a string using below code base. This code base should be able to handle a use case where a user has entered something like 11:11 then it will not add any leading zero to the string.

        Dim str1 As String = Console.ReadLine()
        str1 = str1.PadLeft(5, "0"c)

        Console.WriteLine(str1.PadLeft(4, "0"c))

Open in new window

Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
Use TimeSpan.TryParse() and TimeSpan.ToString():
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ts As TimeSpan
        If TimeSpan.TryParse(TextBox1.Text, ts) Then
            Dim formattedTime As String = ts.ToString("hh\:mm")
            Label1.Text = formattedTime
            MessageBox.Show("Invalid Time")
        End If
    End Sub

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Thanks very much
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.