ImTheBoss
ImTheBoss

Reputation: 337

How to convert string to date or datetime vb.net

How can I convert my strings into a date or datetime datatype in vb.net? These are my strings that are date and time with this format:

Dim sDate,sTime String
Dim myDate,myTime,dateToSave as Date

sDate = '11/25/13'
sTime = '16:30:05'

I wanted to convert it to a date with this expected output:

myDate = '11/25/2013'
myTime = '16:30:05'
dateToSave = '11/25/2013 16:30:05'

How can I do this so that I can save it to sql table with datatype of datetime?

Upvotes: 0

Views: 2116

Answers (3)

Wiley
Wiley

Reputation: 82

dim QueryString as string = "Update someTable set someDate = '" & sDate & " " & sTime & "'"

or dim datetosave as string = sDate & " " & sTime

dim QueryString as string = "Update someTable set someDate = '" & dateToSave & "'"

Upvotes: 0

rory.ap
rory.ap

Reputation: 35260

Something as simple as myDate = CDate(sDate & " " & sTime) will work. But also, if you're going to insert or update a SQL Server table that has a column with one of the date/time data types, you can just insert the value as is and it will be stored with the proper data type:

String.Format("INSERT INTO MyTable (MyDateColumn) VALUES({0})", dDateToSave)

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Declare myDate, myTime and dateToSave as DateTime. Then you can use DateTime.TryParse or DateTime.TryParseExact to convert a string into a DateTime.

PS: I'm reading the sql-server tag in your question. Please remember to pass the values to the database server using parameterized queries - this will save you the next question about how to insert dates and times into the database.

Upvotes: 2

Related Questions