且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取错误:字符串未被识别为有效的DateTime在c#

更新时间:2022-12-11 10:04:13

AndreyAkinshin已经解释了真正的问题。我想添加这个作为一个答案,如果他让我..



两个 DateTime.Parse Convert.ToDatetime 方法默认使用您的 CurrentCulture 设置。



而您的 CurrentCulture 只能 dd / MM / yyyy MM / dd / yyyy 格式。它不能同时使用这两种格式作为标准的日期和时间格式,因为当您收到 01/01/2014 之类的字符串时,不能 code>。



没有DateTime方法可以解决您的问题。即使您使用 DateTime。 TryParseExact 重载,格式为 string [] ,它会以您的数组匹配的第一个成功格式解析您的字符串。 / p>

tl; dr



你必须知道您的数据格式如何。


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.