如何在vb.net中将日期从字符串转换为日期?

时间:2012-12-14 10:01:55

标签: asp.net vb.net

我的日期是字符串格式,如“14-12-2012”。将日期从字符串转换为日期后,它就像这样给出“#12/14/2012#”

然后我试图在数据库中保存日期,这是错误的。

Dim queryString As String = "UPDATE [ARIBA_CUST_ADMIN] SET [CUST_CRED_ID] = '" + eCustomer.CUST_CRED_ID + "',[CUST_NAME] = '" + eCustomer.CUST_NAME + "',[STREET1] = '" + eCustomer.STREET1 + "',[STREET2] = '" + eCustomer.STREET2 + "',[CITY] = '" + eCustomer.CITY + "',[State] = '" + eCustomer.STATE + "',[POSTAL_CD] = '" + eCustomer.POSTAL_CD + "',[COUNTRY] = '" + eCustomer.COUNTRY + "',[CUST_CRED_DOMAIN] = '" + eCustomer.CUST_CRED_DOMAIN + "',[SUBCHARGE] = '" + eCustomer.SUBCHARGE + "',[TAX_AT_LINE] = '" + eCustomer.TAX_AT_LINE + "',[PO_FLIP] = '" + eCustomer.PO_FLIP + "',[STATUS] = '" + eCustomer.STATUS + "',[CONFIMRATIONS] = '" + eCustomer.CONFIMRATIONS + "',[SHOP_NOTICES] = '" + eCustomer.SHOP_NOTICES + "',[INVOICE_TYPE] = '" + eCustomer.INVOICE_TYPE + "',[EFFECTIVE_DATE] = " + eCustomer.EFFECTIVE_DATE + ",[DISTRIBUTION_XML] = '" + eCustomer.DISTRIBUTION_XML + "' WHERE [CUST_ID] = " + eCustomer.CUST_ID

2 个答案:

答案 0 :(得分:1)

Dim dateString, format As String
        Dim result As Date
        Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture

        ' Parse date and time with custom specifier.
        dateString = "20121216"
        format = "yyyyMMdd"


        result = Date.ParseExact(dateString, format, provider)

这将以您在格式变量中指定的任何格式输出日期。

对于您希望使用的日期格式:

format = "dd-MM-yyyy"

答案 1 :(得分:1)

你应该使用参数化查询然后你不需要担心特定的格式,你只需要传递一个日期作为参数(假设你的数据库列是一个日期类型 - 如果不是这样,它应该是:)

沿着这些方向的东西

Dim d as Date= new Date(2012, 12, 3)'or ParseExact from a string in a known format
Dim sql As String = "INSERT INTO foo (DateValue) VALUES (@DateValue)"

Using cn As New SqlConnection("Your connection string here"), _
    cmd As New SqlCommand(sql, cn)

    cmd.Parameters.Add("@DateValue", SqlDbTypes.Date).Value = d
    cmd.ExecuteNonQuery
End Using

查看this question了解更多信息