繁体   English   中英

c#csvhelper如何将字符串解析为日期时间对象

[英]c# csvhelper how to parse string to datetime object

我有以下 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; }
}

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

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

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM