【问题标题】:C# How to convert irregular date and time String into DateTime?C#如何将不规则的日期和时间字符串转换为DateTime?
【发布时间】:2010-12-14 07:21:38
【问题描述】:

我有一个程序可以将不规则的日期和时间字符串转换为系统日期时间。

但由于系统无法识别不规则字符串,因此.ParseExact、toDateTime和TryParse方法不起作用。

程序需要转换的日期时间字符串只有2种:

 Thu Dec  9 05:12:42 2010
 Mon Dec 13 06:45:58 2010

请注意,单个日期有一个双倍间距,我使用 .replace 方法将单个日期转换为Thu Dec 09 05:12:42 2010

有人可以就代码提供建议吗?谢谢!

代码:

        String rb = re.Replace("  ", " 0");

        DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);

        Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));

【问题讨论】:

    标签: c# datetime time


    【解决方案1】:

    我真的会避免使用正则表达式并使用已经内置的 .NET(TryParseExact 方法和 date formats):

    DateTime result;
    string dateToParse = "Thu Dec  9 05:12:42 2010";
    string format = "ddd MMM d HH:mm:ss yyyy";
    
    if (DateTime.TryParseExact(
        dateToParse, 
        format,
        CultureInfo.InvariantCulture, 
        DateTimeStyles.AllowWhiteSpaces, 
        out result)
    )
    {
        // The date was successfully parsed => use the result here
    }
    

    【讨论】:

    • @Darin:正则表达式仅用于从较大的字符串中提取日期。见他的earlier question
    • @AgentConundrum,据我所见,他正在使用正则表达式替换原始字符串中的空格,在一天的开始时添加 0,等等......那些不需要正确格式的东西字符串。
    • @Darin:你是对的。我忽略了第二个正则表达式。对此感到抱歉。
    • @Darin 第一个正则表达式实际上与时间日期的转换有关,我将删除它....
    • @JavaNoob,这里的重点是您应该删除所有正则表达式,并且永远不要将它们用于此类任务:-)
    【解决方案2】:

    您应该将日期时间的部分捕获到匹配对象中的捕获组中,然后以您想要的任何方式重构它们。

    您可以将此 Regex 语句与命名组一起使用以使其更容易

    ((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4})
    

    【讨论】:

      【解决方案3】:

      这是您可以尝试的示例代码:

              var str = "Thu Dec  9 06:45:58 2010";
              if (str.IndexOf("  ") > -1)
              {
                  str = str.Replace("  ", " ");
                  DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null);
              }
              else
              {
                  DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null);
              }
      

      【讨论】:

        猜你喜欢
        • 2013-05-04
        • 2013-03-12
        • 1970-01-01
        • 1970-01-01
        • 2011-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多