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?

4 Years
Discussion Span
Last Post by jakub.peciak

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)


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?

Edited by Begginnerdev


This work for me

TextBox1.Text = 116

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

Click Here

Edited by Reverend Jim: Fixed formatting


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

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".

Edited by tinstaafl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.