vanishp2019
vanishp2019

Reputation: 21

How to output dates into CSV file in DD/MM/YYYY format instead of DD/MM/YYYY HH:MM:SS

Non-dev here attempting to clear out the formatting for dates. Looking for a check on the C# code created by a contractor.

This is new code which is being used to convert a JSON object into a CSV format. The contractor has used Newtonsoft and Newtonsoft.Linq, there is also a CSVhelper function being used.

string webData = System.Text.Encoding.UTF8.GetString(raw);

var records = JsonConvert.DeserializeObject<IList<JournalImport>>(webData, new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" });

using (var writer = new System.IO.StreamWriter(journalsCsvSFD.OpenFile()))
using (var csv = new CsvHelper.CsvWriter(writer))

My current CSV outputs "26/06/2019 12:18:56".

Expected results wanted "26/06/2019"

Upvotes: 2

Views: 3797

Answers (3)

David Specht
David Specht

Reputation: 9074

You can add formatting options.

using (var writer = new System.IO.StreamWriter(journalsCsvSFD.OpenFile()))
using (var csv = new CsvHelper.CsvWriter(writer))
{
    csv.Configuration.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "dd/MM/yyyy" };
    csv.WriteRecords(records);
}

Upvotes: 1

Kalten
Kalten

Reputation: 4302

CsvHelper allow you to create custom type converter. So you can do it for DateTime and format it as you want.

void Main()
{
    string webData = "[{\"date\":\"01/01/2018\",\"name\":\"toto\"}]";
    var records = JsonConvert.DeserializeObject<IList<JournalImport>>(webData, new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" });
    using (var writer = new System.IO.StreamWriter(File.Create(@"toto.csv")))
    using (var csv = new CsvHelper.CsvWriter(writer))
    {
        csv.Configuration.TypeConverterCache.AddConverter<DateTime>(new DateTimeCOnverter());
        csv.WriteRecords(records);
    }
}

public class JournalImport
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
}

public class DateTimeCOnverter : ITypeConverter
{
    public object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
    {
        throw new NotImplementedException();
    }

    public string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        if (value is DateTime date)
        {
            return date.ToString("dd/MM/yyyy");
        }
        return value?.ToString();
    }
}

Upvotes: 0

Zach Favakeh
Zach Favakeh

Reputation: 227

Getting Excel to correctly format things on import is finicky. You can tell it to do one thing and it will do something completely different. Anyway, highlight the entire column of times, right click->format cells. Under the "Number" tab, instead of going to the "Time" category try going to the "Custom" category and I think you will be able to find what you are looking for.

Upvotes: 0

Related Questions