簡體   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