簡體   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