Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CsvHelper changing how dates and times are output

Tags:

c#

.net

csvhelper

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?

like image 934
TheEdge Avatar asked Sep 19 '16 02:09

TheEdge


1 Answers

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); 
like image 193
Pylyp Lebediev Avatar answered Sep 23 '22 04:09

Pylyp Lebediev