简体   繁体   中英

C# Asp.net Convert.toDateTime(datevalue) gives error with different cultureinfo need datepattern look like 5/1/2012 12:00:00 AM

In my Asp.net Website i have two textboxes (txtstartdate, txtenddate) applied JQquery Datepicker which popups gives date in format (" 05/24/2012 "). Work fine for cultureInfo(" en-US "), when i change to (" de ") ie German its give error "System.FormatException: String was not recognized as a valid DateTime." . In my code behind file i am writing this code

 string sDate = txtstartdate.Text;  //  05/01/2012 (debugging gives this values)
 string eDate = txtenddate.Text;    //   05/24/2012 (debugging gives this values)

 DateTime startdate = Convert.ToDateTime(sDate); //  5/1/2012 12:00:00 AM
 DateTime enddate = Convert.ToDateTime(eDate);   //  5/24/2012 12:00:00 AM

My requirement is datetime variable must give date of format 5/1/2012 12:00:00 AM whatever be the cultureinfo set doesnt matter to the date.So that i can execute select query in MsSql Server existing table having column datatype Datetime with data (5/1/2012 12:00:00 AM) formart

After Changing the CultureInfo (from Masterpage dropdownlist) Englsih to German gives error Have tried this but not working

 DateTime startdate = DateTime.ParseExact(sDate, "M/d/yyyy", null); 
 //tried also "MM/dd/yyyy"

Note: Set any cultileinfo, but the datetime pattern alwayz be 5/1/2012 12:00:00 AM ie en-US culture

You could try using "MM/dd/yyyy" as your format string when you call ParseExact , assuming that you're sure the input will always be in that format.

Alternatively, try using Convert.ToDateTime(yourString, CultureInfo.InvariantCulture) instead.

I think in this case you have to set the altFormat of your calendar to the format used by SQL server. Then, you can use a hidden field to store the altDate for each of your date pickers. When you submit, the value of the altField , in the correct format would be sent to your server instead of the culture-specific value that's displayed to the user.

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