简体   繁体   中英

c# csvhelper how to parse string to datetime object

I have the following csv

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

and the following code

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 is working fine when converting to string However when I try to parse to DateTime I get Exception

ie

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

I get: "String was not recognized as a valid DateTime."

You can use a map class to give the format of the date and time that you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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