user829174
user829174

Reputation: 6362

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

i.e

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."

Upvotes: 0

Views: 2867

Answers (1)

Harikesh
Harikesh

Reputation: 158

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

Upvotes: 1

Related Questions