我试图从日志文件日期格式转换为对象dateTime
但是我找不到要转换它的字符串格式?
有人可以帮我格式化:
日志文件行: - 已开始2014年12月28日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
{
}
}
Run Code Online (Sandbox Code Playgroud)
异常:"字符串未被识别为有效日期时间
这里有三个问题:
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 );
}
Run Code Online (Sandbox Code Playgroud)
请注意,您可以()完全省略它们,它们确实没有任何好处,但它们确实使正则表达式更容易阅读(恕我直言).
| 归档时间: |
|
| 查看次数: |
159 次 |
| 最近记录: |