我收到此错误消息:
字符串未被识别为有效的日期时间。堆栈:位于 System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
我认为当我尝试转换为
DateTime
(以 0 开头的时间字符串)时,就会发生这种情况:
我正在查看此链接:parseExact 未识别为有效日期时间
我有一个从日志文件中读取的脚本,我需要查看日期是否在我关心的范围内。我不想用正则表达式检查每一行,看看日期是否正确地在开头有两个 00,因为太多了。如何将其转换为
DateTime
以便其行为正确?我们不想编辑日志或记录。
string serverPath = @"\\\\" + serverName;
string logNameFull = logName + ".txt";
string partialPath = @"\build\logs\";
string combinedPath2 = partialPath + logNameFull;
Uri serverUri = new Uri(serverPath + combinedPath2);
string finalPath = serverUri.LocalPath;
DataTable dataTable = ReadDataTable(finalPath);
foreach (DataRow row in dataTable.Rows)
{
try
{
if (Regex.IsMatch((row[startTimeHeader]).ToString(), @"^\d+")) //date starts with number..filter out rows that have general logging instead of dated table entries
{
string tmpStartDT = (row[startTimeHeader]).ToString();
startDate = DateTime.ParseExact(tmpStartDT, "MM/dd/yyyy HH:mm:ss", provider); //problem line
}
}
catch (Exception ex)
{
Console.WriteLine("Caught exception for row: {0} CName:{1} on line close to:{2} server:{3} logname:{4} startDate:{5}", row.ToString(), cName, debug_i, serverName, logName, row[startTimeHeader]);
Console.WriteLine("Message: " + ex.Message + " stack:" + ex.StackTrace);
}
} // foreach
打印出来:
捕获行异常:System.Data.DataRow CName:CopyLogFile 在线接近:475 server:mach62 logname:ParseLogStats startDate:04/14/2024 0:38:07
日志中的行是这样的:
04/14/2024 0:38:07 04/14/2024 0:38:13 Sun 00:00:06 6 Success v24.1 Incr Stage_M 0 967 0 0 0 0 0 0 0 I:\logs\Stage_.log
Message: String was not recognized as a valid DateTime. stack: at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
at BuildStatusVerification.BuildStatusVerification.ParseLogFile(String codeFreezeTime, String startTimeHeader, String serverName, String logName, String cName, String cValue, String field1, String comparison1, String val) in C:\BuildStatusVerification\BuildStatusVerification\BuildStatusVerification.cs:line 150
使用
H:mm:ss
作为格式说明符而不是 HH:mm:ss
,以便它接受单位数小时。
修剪 tmpStartDT
以删除尾随空格。
tmpStartDT = tmpStartDT.Replace(" ", " ");
将双空格更改为单空格。