从数据表中解析错误的DateTime列

问题描述 投票:0回答:2

我已经将一个非常大的csv文件转换为数据表,现在我正在解析每一列。我遇到了一个问题,其中特定列中的数据不正确。假设它是一个日期,即1/19/2020,但它具有1/1/0001,所以它使我的解析失败。我想做的是在写回表之前删除表中的行。

DateTime checkDate = new DateTime(2018, 01, 01, 0, 0, 0);
for(int i = dt.Rows.Count-1; i >= 0; i--)
{
    DataRow row = dt.Rows[i];
    DateTime AccountInformationDate = DateTime.Parse(row["AccountInformationDate"].ToString());

    if (DateTime.Compare(checkDate, AccountInformationDate) > 0)
    {
         row.Delete();
         counter_skipped++;
     }
}
dt.AcceptChanges();

我尝试解析日期时遇到异常。

c# datatable
2个回答
0
投票

您可以使用DateTime.TryParse检查日期字符串是否正确。


0
投票

使用DateTime.TryParse检查输入是否有效。该解决方案假定您仅在输入为有效DateTime.TryParse的情况下才删除该行;根据需要调整它。

DateTime
© www.soinside.com 2019 - 2024. All rights reserved.