为什么不能将其识别为有效的日期时间? [英] Why is this not recognized as a valid datetime?
问题描述
我有以下代码行:
DateTime dt1 = DateTime.ParseExact( 2017/04 / 09 2:44 PM, yyyy / MM / dd h:mm tt,System.Globalization.CultureInfo.InvariantCulture);
您可以看到日期时间和格式匹配(至少看起来匹配),但是转换时仍然出现错误:
字符串未被识别为有效的DateTime。
不确定使用它的位置,但是输入中有一些不可见的unicode字符。尝试复制粘贴此方法,它将起作用:
DateTime dt1 = DateTime.ParseExact( 2017/04/09 2: 44 PM, yyyy / MM / dd h:mm tt,System.Globalization.CultureInfo.InvariantCulture);
进一步挖掘,在/和0之间有一个 E2 80 8E,另一个在2. 根据unicode表 ,这是从左到右的标记。
一种可行的方法是删除您不希望看到的所有字符:
var input = 2017/04/09 2:44 PM;
var sanitizedInput = Regex.Replace(input,@ [^ \w:/],string.Empty);
DateTime dt1 = DateTime.ParseExact(sanitizedInput, yyyy / MM / dd h:mm tt,System.Globalization.CultureInfo.InvariantCulture);
I have the following line of code:
DateTime dt1 = DateTime.ParseExact("2017/04/09 2:44 PM", "yyyy/MM/dd h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
As you can see the datetime and the format matches (well at least it appears to match), yet I still get an error when converting:
String was not recognized as a valid DateTime.
Not sure where you took it, but there are a few invisible unicode characters in your input. Try copy-pasting this and it'll work:
DateTime dt1 = DateTime.ParseExact("2017/04/09 2:44 PM", "yyyy/MM/dd h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
Digging further, there is a "E2 80 8E" between / and 0, and another one just before the 2. According to the unicode table, this is "left-to-right mark".
One way to make it work is to remove all the characters you don't expect to see:
var input = "2017/04/09 2:44 PM";
var sanitizedInput = Regex.Replace(input, @"[^\w:/ ]", string.Empty);
DateTime dt1 = DateTime.ParseExact(sanitizedInput, "yyyy/MM/dd h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
这篇关于为什么不能将其识别为有效的日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!