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

浪尽此生 提交于 2019-12-09 01:54:30

问题


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.


回答1:


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.




回答2:


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))
{ }



回答3:


You can't tell programatically whether the date is dd/mm/yyyy or mm/dd/yyyy unless they are obviously invalid, e.g. 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, e.g.

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.



来源:https://stackoverflow.com/questions/27061880/getting-error-string-was-not-recognized-as-a-valid-datetime-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!