简体   繁体   中英

how to convert date from string to date in vb.net?

I have date in string format like "14-12-2012". After converting the date from string to date it is giving like this "#12/14/2012#"

Then I am trying to save date in database it is giving error.

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)

This will output the date in whatever format you specify in the format variable.

For the date format you want you'd use:

format = "dd-MM-yyyy"

You should use a parameterised query then you don't need to worry about the specific format, you just pass a date as the parameter (Assuming your DB column is a date type - it should be if it isn't):

Something along these lines

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

Have a look at this question for more info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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