Search code examples
c#.netcsvhelper

CsvHelper changing how dates and times are output


I am using CsvHelper to write some CSV files and want to change the format of my dates and times to something specific. Following the advice from https://stackoverflow.com/a/31817621/223742 I can successfully create maps for each of my classes.

However it has the distinct disadvantage that I now need to create custom maps for all the classes that I want to export. As I always want all the fields exported this becomes a maintenance nightmare as I have to amend maps each time.

So is there any simple way to tell CsvHelper to write all dates and times using a specific format?


Solution

  • You can set it globally per type using TypeConverterOptionsFactory.

    void Main()
    {
        using (var stream = new MemoryStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        using (var csv = new CsvWriter(writer))
        {
            var options = new TypeConverterOptions
            {
                Format = "o"
            };
            TypeConverterOptionsFactory.AddOptions<DateTime>(options);
    
            csv.WriteField(DateTime.Now);
            csv.NextRecord();
            writer.Flush();
            stream.Position = 0;
    
            reader.ReadToEnd().Dump();
        }
    }
    

    Output:

    2016-09-19T11:01:41.5507054-05:00