I have a time as a string saved as HoursMinutes example 1642 (16:42) and I tried to convert it to date as Hours:Minutes with following code:

Dim dt As Date
Dim s As String
s = "1642"
dt = CDate(Format(s, "00:00"))

but the result is: 00:00 instead of 16:42

Any ideas?

Dates will not hold just hours and mintutes, you will have to set a default month,day,year

    Dim s As String = "1642"
    Dim hourPortion As String = s.ToCharArray(0, 2)
    Dim minPortion As String = s.ToCharArray(2, 2)
    Dim dt As New DateTime(1900, 1, 1, CInt(hourPortion), CInt(minPortion), 0)

    MsgBox(dt.ToShortTimeString())

Will do what you are wanting, but this is a very inefficient way of storing date/time.

This will only work if 4 digit hour/second strings exits - the code will break if there is any change in data.

May I ask why you are storing just hour/minutes?

This work for me

TextBox1.Text = 116

Dim Time1 As Date = CDate(Format(TextBox1.Text, "00:00"))

Click Here

I think this will give you want you want:

    Dim s As String = "1642"
    Dim dt As TimeSpan
    dt = TimeSpan.Parse("00:" + s.Substring(0, 2) + ":" + s.Substring(2, 2))
    MessageBox.Show(dt.ToString)

Your output is 00:16:42. I think this is the closest you can get with a built-in function.

But if your string is always in a known format(i.e. mmss) just rebuild the string with a colon in it s.Substring(0, 2) + ":" + s.Substring(2, 2). If your string is coming from a textbox, I'd suggest uising the masked textbox, which will give you a string in the right format automatically validated, a mask like this would work, "00:00".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.