SQL datetime to string format

2019-07-29 10:15发布

问题:

I have some code which declares an object variable, and this variable is assigned a value from an existing database field.

Dim datestart As Object
datestart = dbToDate(dr("DateStart"))

The variable is then passed through a function which checks whether or not it is null, and then converts it into datetime data type.

     Public Shared Function dbToDate(o As Object) As DateTime

    If o Is DBNull.Value Then
        Return Nothing

    Else
        Return Convert.ToDateTime(o)

    End If
End Function

The last thing I need to do with it is convert it into a date formatted string, DD/MM/YYYY, so that I can insert it into a new database.

The function that I have so far is

Public Shared Function sqlDate(dt As DateTime) As String

    Return "'" & Format(dt, "yyyyMMdd") & "'"

End Function

However, when I run the code, I get the following error message

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Why is this, and how do I fix it?

回答1:

Simply, you can use toString function. Also check your timezone. The problem might be in the time zone setting.

Hope you are passing date as string to database, Try to pass date as Datetime variable rather than string

Public Shared Function sqlDate(dt As DateTime) As String

    Return dt.toString("yyyy-MM-dd")

End Function

For your Ref: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx