CsvHelper changing how dates and times are output
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
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);
For me it was easier to use CsvHelper attributes on class.
[Format("yyyy-MM-dd")]
did the job for datetime formatting.
namespace BarNamespace
{
using System;
using CsvHelper.Configuration.Attributes;
public class Foo
{
[Name("ColumnName1")]
[Format("yyyy-MM-dd")]
public DateTime Date { get; set; }
[Name("ColumnName2")]
public string Col2{ get; set; }
[Name("ColumnName3")]
public long Col3{ get; set; }
}
}