【问题标题】:Why is this not recognized as a valid datetime?为什么这不被识别为有效的日期时间?
【发布时间】:2017-06-10 16:02:52
【问题描述】:

我有以下代码行:

DateTime dt1 = DateTime.ParseExact("‎2017/‎04/‎09 ‏‎2:44 PM", "yyyy/MM/dd h:mm tt", System.Globalization.CultureInfo.InvariantCulture);  

您可以看到日期时间和格式匹配(至少看起来匹配),但在转换时我仍然收到错误:

字符串未被识别为有效的日期时间。

【问题讨论】:

    标签: c# datetime


    【解决方案1】:

    不确定您将其带到何处,但您的输入中有一些不可见的 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 之前还有一个。According to the unicode table,这是“从左到右的标记”。

    使其工作的一种方法是删除所有您不希望看到的字符:

    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);
    

    【讨论】:

    • 问题是我从资源管理器的“上次保存日期”值中得到它。原来的字符串有 '?'我用 string.Empty 替换的符号
    • @Eminem 如果您无法从源代码中获得干净的字符串,一种解决方案是对其进行清理。查看我的编辑
    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多