SQL日期时间转换为字符串格式 [英] SQL datetime to string format

查看:1967
本文介绍了SQL日期时间转换为字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码声明一个对象变量,并且从现有数据库字段为该变量分配了一个值。

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"))

然后将该变量通过一个函数传递,该函数检查该变量是否为null,然后将其转换为datetime数据类型。

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

我要做的最后一件事是将其转换为日期格式的字符串DD / MM / YYYY,以便我可以插入

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


将varchar数据类型转换为datetime数据类型导致值超出范围。

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?

推荐答案

简单来说,您可以使用 toString 函数。同时检查您的时区。问题可能出在时区设置。

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

希望您将日期作为字符串传递给数据库,尝试将日期作为Datetime变量而不是字符串传递

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

供您参考: https://msdn.microsoft.com/zh-CN/library/8kb3ddd4( v = vs.110).aspx

这篇关于SQL日期时间转换为字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆