【问题标题】:Converting "August 2012" to DateTime object with TryParseExact使用 TryParseExact 将“August 2012”转换为 DateTime 对象
【发布时间】:2017-10-13 17:31:08
【问题描述】:

我正在尝试将格式为“2012 年 8 月”的字符串解析为 DateTime 对象。该字符串来自 DataTable 中的列名。

string columnName= row[col].ToString(); // "August 2012"

最初我尝试使用 DateTime.TryParse() ...

bool result = DateTime.TryParse(row[col].ToString, out convertedDateTime);

但它一直返回错误。所以接下来我尝试使用 DateTime.TryParseExact 使用正确的文化格式,如here 所述...

CultureInfo enUS = new CultureInfo("af-ZA");
DateTime.TryParseExact(row[col].ToString(), "y", enUS, DateTimeStyles.None, out columnNameAsDate)

但是,这也一直返回 false。我究竟做错了什么?我不能将 August 2012 格式的字符串解析为 DateTime 对象吗?

【问题讨论】:

    标签: c# datetime datetime-format tryparse


    【解决方案1】:

    这应该会给你预期的日期。

    string columnName= row[col].ToString();  // ==> August 2012
    CultureInfo enUS = new CultureInfo("en-US");
    DateTime.TryParseExact(columnName, "MMMM yyyy", enUS, DateTimeStyles.None, out columnNameAsDate);
    

    首先:您应该指定确切的文化。在af-ZA 文化中,一年的第八个月被命名为“Augustus”而不是“August”,这当然会失败。

    第二:您应该传递正确的格式规范以获得完整的月份名称 (MMMM) 和年份 (yyyy)。

    【讨论】:

      【解决方案2】:

      我会先拆分字符串:

      DateTime outDate = new DateTime();
      string[] words = columnName.Split(' ');
      if(words.Length>1){
         string month = words[0].Substring(0,3);
         string year = words[1];
         outDate = DateTime.ParseExact(month+' '+year, 
         "MMM yyyy", System.Globalization.CultureInfo.InvariantCulture);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-27
        • 1970-01-01
        相关资源
        最近更新 更多