Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format DateTimes #868

Closed
BrianVallelunga opened this issue Dec 7, 2017 · 4 comments
Closed

Format DateTimes #868

BrianVallelunga opened this issue Dec 7, 2017 · 4 comments

Comments

@BrianVallelunga
Copy link

BrianVallelunga commented Dec 7, 2017

I am trying to format date times in a certain manner, but haven't been able to get it working since I upgraded to the latest version.

I read the docs and I think the right thing to do is:

csv.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "MM/dd/yyyy HH:mm:ss" };

I would expect that to work, but what I'm getting is output like: "12/6/2017 4:01:10 AM" (the AM is the issue here). So I think it's just not being used, but I'm unsure of what else to try.

@JoshClose
Copy link
Owner

Do you want it applied to a single field or to all DateTime type fields?

@BrianVallelunga
Copy link
Author

BrianVallelunga commented Dec 8, 2017

I thought what I was doing would apply it to all DateTime fields, but that didn't work.

@JoshClose
Copy link
Owner

This works for me. What am I doing differently than you here?

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))
    {
        csv.Configuration.RegisterClassMap<TestMap>();
        csv.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "MM/dd/yyyy HH:mm:ss" };
        
        var records = new List<Test>
        {
            new Test { Id = 1, Name = "one", DateTime = DateTime.Now },
        };
        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 DateTime DateTime {get; set; }
}

public sealed class TestMap : ClassMap<Test>
{
    public TestMap()
    {
        Map(m => m.Id);
        Map(m => m.Name);
        Map(m => m.DateTime);
    }
}

@JoshClose
Copy link
Owner

Closing due to inactivity.

ascott18 added a commit to IntelliTect/Coalesce that referenced this issue Jan 17, 2020
…ur tests broke when I switched the builds to the ubuntu agent. JoshClose/CsvHelper#868
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants