c# - 日期的字符串格式

标签 c#

我正在尝试将日志文件日期格式转换为对象日期时间

但是我找不到要转换的字符串格式?

谁能帮我解决格式问题:

日志文件行:- 开始于 28/12/2014 16:53:47.48 "

我的代码:

 string pattern1 = @"(\d+)[/](\d+)[/](\d+)";
 Match match1 = Regex.Match(lineOfLog, pattern1, RegexOptions.IgnoreCase);
 if (match1.Success)
 {
   string dateFormat = "dd/MM/yyyy HH:mm:ss.zzz";
   string dateString = match1.Groups[1].Value;
   DateTime date = new DateTime();
   try
   {
    date = DateTime.ParseExact(dateString, dateFormat, CultureInfo.InvariantCulture);
   }

    catch
    {

    }

  }

异常:“字符串未被识别为有效的日期时间

最佳答案

这里有三个问题:

  • 正则表达式没有捕获完整的日期和时间
  • 您只是得到正则表达式结果的一部分(即您得到的是单个组,而不是整个匹配项的值)
  • 您的格式字符串使用 zzz 而它应该是 FF 表示百分之一或 FFF 表示千分之一

尝试这样的事情:

string lineOfLog = "- Started 28/12/2014 16:53:47.48";
string dateFormat = "dd/MM/yyyy HH:mm:ss.FF";           
string pattern1 = @"(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+)\.(\d+)";

Match match1 = Regex.Match( lineOfLog, pattern1, RegexOptions.IgnoreCase );
if( match1.Success )
{
    var dateString = match1.Value; // note the change here
    var d = DateTime.ParseExact( dateString, dateFormat, CultureInfo.InvariantCulture );
}

请注意,您可以完全省略 (),它们实际上没有任何用处,但它们确实使正则表达式更易于阅读(恕我直言)。

关于c# - 日期的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27690577/

相关文章:

c# - 在图片框上绘制位图背景时出现内存不足错误

c# - 我可以通过同一个 DataContext 对象同时访问多个表吗?

c# - Parallel.ForEach 使用 Thread.Sleep 等效

c# - 处理多个进程的关闭

c# - 如何访问 System.Windows.Forms.Design.ParentControlDesigner?

c# - 混合模式程序集是针对 'v2.0.50727' 错误构建的

c# - 将 AutomationID 与 ListView 一起使用

c# - Windows Phone 8.1 后台任务在完成前关闭

C# - 使用 Dapper 构建分层数据结构

c# - Winform布局完成后触发事件