简体   繁体   中英

Datetime Update format error Asp.Net

I have an italian format datetime string like this:

23/03/2012

the sql command of this update is this in the datetime part:

DateTime.ParseExact(Reg_tes.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)

This works on my Sql server(Italian language) but if i make this on my server(English language) gives me this error:

"the conversion of a varchar data type to a datetime data type resulted in an out-of-range value"

How can I resolve this?

You should always use parameterized queries to prevent sql-injection and localization issues like this.

So i assume that you are passing this datetime as string to the database.

using(var con = new SqlConnection("connection-string"))
using(var cmd = new SqlCommand("UPDATE dbo.TableName SET DateColumn=@DateColumn WHERE PK=@PK", con))
{
    DateTime reg_tes = DateTime.ParseExact(Reg_tes.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
    cmd.Parameters.AddWithvalue("@DateColumn", reg_tes);
    // other parameters ...
    con.Open();
    int affected = cmd.executeNonQuery();
}

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