SQL datetime to string format

ぐ巨炮叔叔 提交于 2020-03-25 05:48:11

问题


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



来源:https://stackoverflow.com/questions/38654241/sql-datetime-to-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!