sharkyenergy
sharkyenergy

Reputation: 4173

vb.net - Formatting a datetime column of a datatable to a yyyy/MM/dd HH:mm string

I dont seem to be able to figure out what is wront in the code. Here is a screenshot to see the error message, the code, and the content of the variable.

and a bigger part of the code:

       For Each value As DataColumn In dt2.Columns
                    If value.DataType = System.Type.GetType("System.DateTime") Then
                        dq = dq & value.ColumnName & " = '" & r2.Item(value.ColumnName).ToString("yyyy/MM/dd HH:mm:ss") & "' and "
                    End If

            Next

enter image description here

what am I doing wrong?

Upvotes: 0

Views: 3454

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460058

That just compiles because you have Option Strict Off(no-go). You have to cast the Object returned from r2.Item(value.ColumnName) to a Date. This also fixes this issue, you can use Field:

r2.Field(Of Date)(value.ColumnName).ToString("yyyy/MM/dd HH:mm:ss")

Since you are german, note that your format string might not give you what you expect but something like 2021.02.23 15:00:24. If you want 2021/02/23 15:00:24 you need to use ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture). See: here

Upvotes: 1

Related Questions