c# - 空字符串 ""何时是有效的日期时间字符串格式?

标签 c# .net parsing datetime datetime-format

看到一个奇怪的问题,在某些系统上,以下代码进入 if 语句(即返回 true),而在其他系统中,它返回 false 并进入 else 语句。我在更改的地方缺少哪些环境条件或框架版本更改?例如 .net Fiddle 返回 true,但我自己的控制台应用程序返回 false。

    DateTime time;
    formatText = "";
    if (DateTime.TryParse (DateTime.Now.ToString(formatText), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out time))
    {
        // If TryParseExact Worked
        Console.WriteLine ("True: " + time.ToString ()); 
    }
    else
    {
        // If TryParseExact Failed
        Console.WriteLine ("Failed to Parse Date");
    } 

最佳答案

DateTime 的字符串表示形式是特定于文化的。

传递空字符串或 null 作为 DateTimeToString 重载的 format 参数是相同的通过standard format specifier "G" - 来自 DateTime.ToString Method (String) 的备注部分msdn 页面:

If format is null or an empty string, the general format specifier, 'G', is used.

您使用的 TryParse 重载尝试使用 IFormatProvider 格式参数中提供的日期和时间格式来解析 DateTime 值 - InvariantCulture 在您的情况下 - 所以当您将 TryParseInvariantCulture 一起使用时,除非您当前区域性的 ShortDatePatternLongTimePattern 属性与 InvariantCulture 中的相同,tryParse 将失败。

关于c# - 空字符串 ""何时是有效的日期时间字符串格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49385474/

相关文章:

c# - 文件的磁盘结构不受支持的错误...找到 11.1,支持 12.0

c# - TableAdapter.update方法,到哪里去了?

.net - 两个面板的 MouseLeave 事件

无法从 Bison 语法文件中检索语义值

json - Nifi Controller 服务JsontreeReader和JsonPath阅读器有什么区别

php - 如何在php中获取图像alt ="..."的值?

javascript - 从代码隐藏调用 .js 文件函数

c# - 使用 Linq 获取列表 <> 的项目数

.net - 与 Nant 签署程序集

.net - 有没有办法记录或拦截第一次机会异常