JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.76k stars 1.07k forks source link

Using Format() attribute for DateTime doesn't appear to be working #839

Closed chrisculver701 closed 6 years ago

chrisculver701 commented 6 years ago

I have the following property set in the class that is being used to define the records being written. [Index(6), Name("ReceivedDate"), Format("d")] public string ReceivedByDate { get; set; } The DateTime always turns out like this 1/2/2017 0:00 When I do DateTime.ToString("d") the format comes out like "1/2/2017" The Index and Name Attributes are working perfectly. I also tried Format("d/M/yyyy")] and got the same result.

What should i be doing differently?

Thanks,

JoshClose commented 6 years ago

This seems to be working fine for me in the latest version.

Code:

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 = DateTime.Now },
            new Test { Id = 2, Name = "two", Date = DateTime.UtcNow },
        };

        csv.WriteRecords(records);

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

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

public class Test
{
    public int Id { get; set; }

    public string Name { get; set; }

    [Index(2)]
    [Name("ReceivedDate")]
    [Format("d")]
    public DateTime Date { get; set; }
}

Output:

Id,Name,ReceivedDate
1,one,11/9/2017
2,two,11/9/2017
chrisculver701 commented 6 years ago

I just realized what is happening. The AutoMapper is moving it to a string and formatting it before it even gets to CsvHelper. Thank you for the response. I really like your CsvHelper library. It has been a big timesaver here.

JoshClose commented 6 years ago

Glad you figured it out, and thanks!