简体   繁体   中英

IIS String was not recognized as a valid DateTime

I have an issue,

I have string date with this format dd/MM/yyyy and then convert it to DateTime object using Convert.ToDateTime(date) it run just fine within VS but when I publish it to IIS it always throws String was not recognized as a valid DateTime .

but if change the format to MM/dd/yyyy it runs fine in IIS but error if run it via VS.

string date =  "19/9/2019"  //"dd/MM/yyyy";
DateTime dt = Convert.ToDateTime(date); //run fine via VS, error in IIS

string date = "09/19/2019" //"MM/dd/yyyy";
DateTime dt = Convert.ToDateTime(date); //run fine via IIS, error in VS

please advice

First of all, "09/19/yyyy" is not a valid string that can be parsed to DateTime , and it should throw exception on IIS either.

Second, Convert.ToDateTime(string) overload uses CurrentCulture settings on your machine. If your VS and IIS in different machines, check their CurrentCulture settings on both machines. I assume they are quite diferent and one of them is not have "dd/M/yyyy" as a standart date format.

On the other hand, to prevent this kind of parsing operations, you can use DateTime.ParseExact method overloads and you can specify exact format and proper (that uses / as a DateSeparator ) culture information.

Aslo be aware that the diffence between M and MM specifiers. For single digit month numbers, MM specifier will generate month number with leading zero (like 09 ) but M specifier won't.

string date =  "19/9/2019";
DateTime myDate = DateTime.ParseExact("dd/M/yyyy", date, CultureInfo.InvariantCulture); 

or

string date =  "19/09/2019";
DateTime myDate = DateTime.ParseExact("dd/MM/yyyy", date, CultureInfo.InvariantCulture); 

You getting error just because server-side default culture is different from development site.

You should either use DateTime.TryParseExact or use DateTime.TryParse specifying the appropriate CultureInfo . (For Eg, the culture of the user.)

You should apply an appropriate CultureInfo to ToString - possibly CultureInfo.InvariantCulture .

Example:

var varDate = DateTime.ParseExact(txtDate.Text, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
DateTime dt3 = Convert.ToDateTime(varDate);

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