简体   繁体   中英

Getting error : String was not recognized as a valid DateTime in c#

Getting error like :

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: String was not recognized as a valid DateTime.

I am using this code :

string datetime = DateTime.Parse(encrypt[1]);

or

string datetime = Convert.ToDatetime(encrypt[1]);

encrypt is a string array

In encrypt[1] I am not sure which format will come in string . i have trace some time come dd/MM/yyyy and sometime MM/dd/yyyy or MM-dd-yyyy or dd-MM-yyyy . I am not sure about format it may from above or another format come.

also use ParseExcept and TryParseExcept . but not get succeeded seems return same error

please give me proper solution.

AndreyAkinshin already explained the real problem. I want to add this as an answer if he lets me..

Both DateTime.Parse and Convert.ToDatetime methods uses your CurrentCulture settings by default.

And your CurrentCulture can have only one of dd/MM/yyyy or MM/dd/yyyy format. It can't have both formats as a standard date and time format because it can't know which format it uses when you get a string like 01/01/2014 .

None of DateTime methods can solve your problem. Even if you use DateTime.TryParseExact overload that takes formats as a string[] , it parses your string with first successful format that matches in your array.

tl;dr

You have to know which format of your data has.

If you don't exactly know what is coming in, you have virtually no change of getting the date format in correctly .

Take this sample:

01/02/2014

Is this the 2nd of January or the 1st of February?

If you do know the formats, you could use TryParseExact and just walk down the list until one matches:

DateTime d;
if (DateTime.TryParseExact(encrypt[1], "dd/MM/yyyy", CultureInfo.InvariantCulture, out d))
{ }
else if (DateTime.TryParseExact(encrypt[1], "yyyy/MM/dd", CultureInfo.InvariantCulture, out d))
{ }

You can't tell programatically whether the date is dd/mm/yyyy or mm/dd/yyyy unless they are obviously invalid, eg if you're expecting dd/mm/yyyy and you get 12/14/2014, then that format can only be mm/dd/yyyy.

However, since you are receiving the data from a HTTP request (question is tagged with MVC), you can find the user's culture and use that to parse the date using, eg

DateTime.Parse("13/12/2014", new CultureInfo("en-GB")); // Works fine.

DateTime.Parse("13/12/2014", Thread.CurrentThread.CurrentCulture)

See http://msdn.microsoft.com/en-us/library/bb882561(v=vs.110).aspx for more information.

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