I can serialize a DataTable to CSV following the example in the FAQ https://joshclose.github.io/CsvHelper/#misc-faq. But I'd like to set configuration options for how DateTime values are serialized. Is there some way I can do this with the CsvConfiguration or do I just need to change the code in the example like this:
foreach (DataRow row in dt.Rows)
{
for (var i = 0; i < dt.Columns.Count; i++)
{
var val = row[i];
if (val is DateTime)
{
// Format DateTimes using the 'sortable' format - https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Sortable
csv.WriteField(val.ToString("s"));
}
else
{
csv.WriteField(val);
}
}
csv.NextRecord();
}
(Apologies if github issue not the right forum for such questions. Thanks for the great library!)
It looks like it is possible by specifying the type converter options for a DateTime type:
TypeConverterOptionsFactory.AddOptions(typeof(DateTime), new TypeConverterOptions() { Format = "s" });
Example usage:
TypeConverterOptionsFactory.AddOptions(typeof(DateTime), new TypeConverterOptions() { Format = "s" });
using (var stream = new StreamWriter("test.csv"))
using (var csv = new CsvWriter(stream))
{
csv.WriteField("test");
csv.WriteField(DateTime.Now);
csv.NextRecord();
}
Hope that helps?
You can also do it in the mapping for the property.
Map( m => m.Property ).TypeConverterOption.Format( "s" );
Most helpful comment
You can also do it in the mapping for the property.