解析字符串到日期时出现奇怪的错误?
当我尝试解析这样的日期时:
DateTime t1 = DateTime.ParseExact("August 11, 2013, 11:00:00 PM", "MMMM dd, yyyy, hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
它工作正常,但当我做这样的事情:
string s ="August 11, 2013, 11:00:00 PM"; DateTime t = DateTime.ParseExact(s, "MMMM dd, yyyy, hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
我收到此错误:
mscorlib.ni.dll中出现“System.FormatException”类型的exception,但未在用户代码中处理
因为你的字符串
string s = "August 11, 2013, 11:00:00 PM";
包含August
月初和月底的0x200e(8206)字符 。 你可以轻松地看到它
var chars = s.ToCharArray();
似乎是一个复制+粘贴问题
您可以通过以下方式删除这些字符:
var newstr = new string(s.Where(c => c <128).ToArray())
哈哈,我找到了。
首先,你的两个代码都没有错。 两者都很好。 只是你的字符串不相等。 你的第二个有一些隐藏的角色。
你的第一个"August 11, 2013, 11:00:00 PM".Lenth
是28
但第二个"August 11, 2013, 11:00:00 PM".Lengt
是33岁
我们试试这段代码;
string s = "August 11, 2013, 11:00:00 PM"; string s1 = "August 11, 2013, 11:00:00 PM"; char[] c = s.ToCharArray(); char[] c1 = s1.ToCharArray(); foreach (var ch in c) { Console.WriteLine(ch); } foreach (var ch1 in c1) { Console.WriteLine(ch1); }
输出将是;
A u g u s t 1 1 , 2 0 1 3 , 1 1 : 0 0 : 0 0 P M ? // <-- What the hell? A u g u s t ? // <-- What the hell? 1 1 , ? // <-- What the hell? 2 0 1 3 , ? // <-- What the hell? ? // <-- What the hell? 1 1 : 0 0 : 0 0 P M
作为解决方案,不要将任何字符串粘贴到代码中:)。
你的第二个字符串有隐藏字符。
运行这个:
string s1 = "August 11, 2013, 11:00:00 PM"; string s2 = "August 11, 2013, 11:00:00 PM"; Console.WriteLine(s1.Length); // 28 Console.WriteLine(s2.Length); // 33
具体来说,作为char数组,第二个是:
s2.ToCharArray(); {char[33]} [0]: 8206 '' // ???? [1]: 65 'A' [2]: 117 'u' [3]: 103 'g' [4]: 117 'u' [5]: 115 's' [6]: 116 't' [7]: 32 ' ' [8]: 8206 '' // ???? [9]: 49 '1' [10]: 49 '1' [11]: 44 ',' [12]: 32 ' ' [13]: 8206 '' // ???? [14]: 50 '2' [15]: 48 '0' [16]: 49 '1' [17]: 51 '3' [18]: 44 ',' [19]: 32 ' ' [20]: 8207 '' // ???? [21]: 8206 '' // ???? [22]: 49 '1' [23]: 49 '1' [24]: 58 ':' [25]: 48 '0' [26]: 48 '0' [27]: 58 ':' [28]: 48 '0' [29]: 48 '0' [30]: 32 ' ' [31]: 80 'P' [32]: 77 'M'
我也受到了这种打击。 在我的情况下,UI自动化测试失败,因为IE似乎自动添加此LRM(从左到右)标记(Firefox和Chrome不会)。 快速删除它的代码:
Regex.Replace(date, @"\u200e", string.Empty)