繁体   English   中英

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

[英]how to convert date from string to date in 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

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变量中指定的任何格式输出日期。

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

format = "dd-MM-yyyy"

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

沿着这些方向的东西

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

有关更多信息,请查看此问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM