Date format from database gets wrong date in vb.net
I'm taking in data from a SQL database and now I'm trying to convert the data to a proper date variable in VB.NET but I don't get the proper format.
Data from the database:
28-FEB-14 01:00:00:0 28-FEB-14 13:00:00:0
The date I get when trying to convert it:
2028-02-14 2028-02-14 12:00:00
The code that is doing the conversion:
Dim theDate As DateTime Dim try1 As Date For i As Integer = 0 To batchCount - 1 If Date.TryParse(dv(i)(0), theDate) = True Then try1 = theDate.ToUniversalTime() End If
Would appreciate all the help I can get.
Firstly, date values in your database should be date types, so when you read them in, you read them into a Date type variable.
If you then want to format that date you can use a ToString overload
Dim theDate as DateTime = dr.item("date") Debug.Writeline(theDate.ToString("yyyy-MM-dd")
Secondly if the date is being stored as a string field in the database (you should not do this but you may have no control over this) it should be in a specific format, so you can use ParseExact to convert this into a date:
Dim dateString As String dateString = DateTime.ParseExact(dr.item("Date"), "dd-MMM-yy HH:mm:ss.f", CultureInfo.CurrentCulture)