获取错误:字符串未被识别为有效的DateTime在c# [英] Getting error : String was not recognized as a valid DateTime in c#

查看:862
本文介绍了获取错误:字符串未被识别为有效的DateTime在c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取错误:


在mscorlib.dll中发生类型为System.FormatException的未处理的异常附加信息:字符串不是确认为有效的DateTime。


我正在使用以下代码:

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

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

加密是一个字符串数组



encrypt [1] 我是不知道哪个格式会出现在字符串中。我有痕迹有一些时间来到 dd / MM / yyyy 和某个时间 MM / dd / yyyy MM-dd-yyyy dd-MM-yyyy 。我不确定格式可能来自上述或另一种格式。



还使用 ParseExcept TryParseExcept 。但没有成功似乎返回相同的错误



请给我正确的解决方案。

解决方案

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.

这篇关于获取错误:字符串未被识别为有效的DateTime在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆