【问题标题】:c# csvhelper how to parse string to datetime objectc# csvhelper 如何将字符串解析为日期时间对象
【发布时间】:2020-09-18 16:14:47
【问题描述】:

我有以下 csv

Date,Stage,Count,Time,Index
20151231,4,3,9:45:3991,1527.23510
20150903,4,613,12:18:0483,1605.56522

还有下面的代码

public List<DailyData> ReadDailyData(string dataFolder)
{
    using (var sr = new StreamReader(dataFolder))
    {
        var reader = new CsvReader(sr);
        return reader.GetRecords<DailyData>().ToList();
    }
}

public class DailyData
{
    public string Date { get; set; }
    public string Stage { get; set; }
    public string Count { get; set; }
    public string Time { get; set; }
    public string Index { get; set; }
}

转换为字符串时,CsvHelper 工作正常 但是,当我尝试解析为 DateTime 时,我得到了异常

public class DailyData
{
    public DateTime Date { get; set; } // should be Date obj
    public string Stage { get; set; }
    public string Count { get; set; }
    public DateTime Time { get; set; } // should be Time obj
    public string Index { get; set; }
}

我得到:“字符串未被识别为有效的日期时间。”

【问题讨论】:

  • 哪一行代码失败了,有什么异常?您在帖子中遗漏了两件重要的事情。
  • 什么异常?什么是类型、堆栈跟踪、消息、InnerException?我们真的无法猜测这些细节。如果我不得不猜测它可能是 FormatException,您是在询问 datetime 和 Time(什么是 Time,也许是 TimeSpan?)类型来猜测字符串的格式。
  • 您是否尝试过使用 CSVHelper 映射?
  • API 的帮助页面有一个名为Type Converter Options 的部分。这可能是您需要的,用于指导 CsvHelper 如何将您的字符串转换为预期的类型。
  • 如果您查看您的数据,我相信您会明白原因。 9:45:3991 不是有效的日期时间。

标签: c# csvhelper


【解决方案1】:

您可以使用地图类来提供所需的日期和时间格式。

class DailyData
{
    public DateTime Date { get; set; } // should be Date obj
    public string Stage { get; set; }
    public string Count { get; set; }
    public DateTime Time { get; set; } // should be Time obj
    public string Index { get; set; }
}

public class DailyDataMap: ClassMap<DailyData> {
        Map(m => m.Date).TypeConverterOption.Format("yyyyMMdd");
        Map(m => m.Stage);
        Map(m => m.Count);
        Map(m => m.Time).TypeConverterOption.Format("H:mm:ffff");
        Map(m => m.Index);
}

【讨论】:

    猜你喜欢
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    相关资源
    最近更新 更多