Csvhelper: WriteRecord<>() : Choosing the format when writing a Date?

Created on 9 Jun 2017  Â·  15Comments  Â·  Source: JoshClose/CsvHelper

How can one write a date field to a csv file and choose the format written when using the WriteRecord<>() method?

Most helpful comment

@klym1 You can set the TypeConverterOptionsCache.

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer))
{
    csv.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new []{"yyyy-MM-dd"};
    csv.WriteRecords(records);
}

All 15 comments

In your ClassMap use Map(m=>m.Prop1).TypeConverterOptions.Format("o"); for
ISO, or another string for others.

On Fri, Jun 9, 2017 at 1:30 PM, chadbruels notifications@github.com wrote:

How can one write a date field to a csv file and choose the format written
when using the WriteRecord<>() method?

—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/JoshClose/CsvHelper/issues/697, or mute the thread
https://github.com/notifications/unsubscribe-auth/AD_ohXRMKjZYgLZWmzDbicnUOg8uLCnLks5sCYE2gaJpZM4N1oZm
.

https://www.screencast.com/t/NQ1JZInv

"CsvPropertyMap does not contain a definition for TypeConverterOptions", so I fell back on attempting to use TypeConverterOption("yyyy-MM-dd"). You can see this did not work if you follow the link above. Please advise - and thank you for quickly responding today. I'm pleasantly surprised to hear from you so quickly.

Here is an example.

void Main()
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvWriter(writer))
    {
        var records = new List<Test>
        {
            new Test { Id = 1, Name = "one", Date = DateTimeOffset.Now },
            new Test { Id = 2, Name = "two", Date = DateTimeOffset.Now },
        };

        csv.Configuration.RegisterClassMap<TestMap>();
        csv.WriteRecords(records);

        writer.Flush();
        stream.Position = 0;

        reader.ReadToEnd().Dump();
    }
}

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTimeOffset Date { get; set; }
}

public sealed class TestMap : CsvClassMap<Test>
{
    public TestMap()
    {
        Map(m => m.Id);
        Map(m => m.Name);
        Map(m => m.Date).TypeConverterOption("o");
    }
}

Output:

Id,Name,Date
1,one,2017-06-13T12:24:19.1959269-05:00
2,two,2017-06-13T12:24:19.1959269-05:00

How do you write a DateTime in the format yyyy-MM-dd?

Just replace "o" with "yyyy-MM-dd" or whatever your preferred format is

On Wed, Jun 14, 2017 at 12:17 PM, chadbruels notifications@github.com
wrote:

How do you write a DateTime in the format yyyy-MM-dd?

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/JoshClose/CsvHelper/issues/697#issuecomment-308482484,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AD_ohUGHcQ36Jmpy0LMl1pl1MBid8pkKks5sEAeMgaJpZM4N1oZm
.

Changing to

Map(m => m.Date).TypeConverterOption("yyyy-MM-dd");

Outputs:

Id,Name,Date
1,one,2017-06-14
2,two,2017-06-14

https://www.screencast.com/t/NQ1JZInv >> I did just that - only difference was including .Index().

Are your u registering the ClassMap with your CsvConfiguration?

On Jun 14, 2017 3:14 PM, "chadbruels" notifications@github.com wrote:

https://www.screencast.com/t/NQ1JZInv >> I did just that - only
difference was including .Index().

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/JoshClose/CsvHelper/issues/697#issuecomment-308530517,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AD_ohRK-hGhPX_bAPHtSbjC4hhWudRbLks5sEDEcgaJpZM4N1oZm
.

Can you post a failing example?

Ahh, I had registered the class map where I was reading the original CSV but I had not done so when I was writing data to a new CSV. It is working for me. Thank you.

The code Map(m => m.Date).TypeConverterOption("o") no longer works as of v12.1.2. TypeConverterOptions is a property, not a method and cannot be invoked as this thread applies.

However, the following _does_ work;

var memberMap = Map(m => m.StatusSetOn);
memberMap.TypeConverterOption.Format("o");

Is there a way to specify format for all properties of a certain type? E.g. I want all DateTimes in all DTOs to have format "yyyy-MM-dd" and don't want to specify each property individually.

@klym1 You can set the TypeConverterOptionsCache.

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer))
{
    csv.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new []{"yyyy-MM-dd"};
    csv.WriteRecords(records);
}

Wow, that's awesome, thanks for the help @AltruCoder

@klym1 You can set the TypeConverterOptionsCache.

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer))
{
    csv.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new []{"yyyy-MM-dd"};
    csv.WriteRecords(records);
}

Thank you, very useful.

If you have DateTime? in the model, then this would be working for ReadRecords, but for WriteRecords have to use <DateTime?>

            // read, in model all the fields are DateTime?
            csvReader.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats =
                new[] { DateTimeConstants.ClientDateFormat };
            var records = csvReader.GetRecords<CsvPropertiesImportItemPropertyFields>();
            // write, in model all the fields are DateTime?
            csvWriter.Configuration.TypeConverterOptionsCache.GetOptions<DateTime?>().Formats =
                new[] { DateTimeConstants.ClientDateFormat };
            csvWriter.WriteRecords(new[] { csvPropertyImportItemPropertyFields });

Was this page helpful?
0 / 5 - 0 ratings