我正在尝试将日志文件日期格式转换为对象日期时间
但是我找不到要转换的字符串格式?
谁能帮我解决格式问题:
日志文件行:- 开始于 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/