CsvHelper changing how dates and times are output

TheEdge picture TheEdge · Sep 19, 2016 · Viewed 7.9k times · Source

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?

Answer

Pylyp Lebediev picture Pylyp Lebediev · Aug 23, 2019

With newer version (12.1.2) of CsvHelper, it can be archived by using TypeConverterOptionsCache

var options = new TypeConverterOptions { Formats = new[] { "MM/dd/yyyy" } };
csvWriter.Context.TypeConverterOptionsCache.AddOptions<DateTime>(options);

Output date

08/24/1991

Version 20 moved TypeConverterOptionsCache from Configuration to Context. So the above becomes

var options = new TypeConverterOptions { Formats = new[] { "MM/dd/yyyy" } };
csvWriter.Context.TypeConverterOptionsCache.AddOptions<DateTime>(options);
csvWriter.Context.TypeConverterOptionsCache.AddOptions<DateTime?>(options);