Link to home
Start Free TrialLog in
Avatar of kirkheaton25
kirkheaton25

asked on

Converting a string to time

I'm using the code below but the result is always 00:00:00.

I've also tried
dim newtime as string = DateTime.ParseExact(0920, "h:mm:ss tt", CultureInfo.InvariantCulture) but get the message: String was not recognized as a valid DateTime.
dim dt as date
dim s as string
s="920"
dt = cdate(format(s,"00:00"))

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Göran Andersson
Göran Andersson
Flag of Sweden 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
Correction:
The constructor for DateTime with three parameters use year, month and day. You have to use the constructor with six parameters to supply hours, minutes and seconds:

Dim t As DateTime = new DateTime(0, 0, 0, h, m, 0)
Avatar of kirkheaton25
kirkheaton25

ASKER

Many thanks for your help.
You could also use TimeSpan.Parse() and add that to a DateTime.  I like the adding a colon approach:

        Dim s As String = "920"
        Dim dt As DateTime = DateTime.Today.Add(TimeSpan.Parse(IIf(s.IndexOf(":") = -1, s.Insert(s.Length - 2, ":"), s)))
        Dim time As String = dt.ToString("HH:mm")
        MessageBox.Show(time)