-1

Hello I am trying to format a date

  • that is in a csv in the format dd / mm / yyyy
  • and would need to put it for ddmmyyyy in a json
    • filtered by a range, example from 01012019 until 31012019

Can anyone give me a suggestion?

Serialization

static void Main(string[] args)
{
    using (var reader = new StreamReader("../database.csv"))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        csv.Configuration.Delimiter = ",";

        var records = csv.GetRecords<Tabela>().ToList();
        // JSON writing
        var json = JsonConvert.SerializeObject(records);
        File.WriteAllText("../database.json", json);

        System.Console.WriteLine(records);
    }
}

Model

class Tabela
{
    public DateTime date { get; set; }
    public String media { get; set; }
    public String client_id { get; set; }
    public String client_name { get; set; }
    public String campaign_id { get; set; }

    public String campaign_name { get; set; }

    public int clicks { get; set; }
    public int impressions { get; set; }
    public Double investment { get; set; }
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • The de-facto standard for JSON dates is the ISO8601 format, ie `YYYY-MM-DD`. There's no justification for using custom, localized formats that would require every client to adopt to them – Panagiotis Kanavos Sep 15 '20 at 14:02
  • In any case, JSON.NET allows you to customize how dates are serialized. There are several SO questions about this, [like this one](https://stackoverflow.com/questions/16320762/dates-without-time-in-asp-net-web-apis-json-output) – Panagiotis Kanavos Sep 15 '20 at 14:04
  • `filtered by a range example 01012019 until 31012019` that string format *doesn't* allow filtering by ranges. Strings are compared using lexicographical ordering and `01012019` always comes before `02011970`, because the date elements are in reverse order. The ISO8601 format allows sorting and filtering because the elements are in the correct order – Panagiotis Kanavos Sep 15 '20 at 14:07

1 Answers1

1

This should be work:

        var validFrom = DateTime.TryParseExact("01012019", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime from);
        var validTo = DateTime.TryParseExact("31012019", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime to);

        if (validFrom && validTo)
        {

            var records = csv.GetRecords<Tabela>()
                .Where(x => x.date >= from && x.date <= to)
                .Select(x => new {
                    date = $"{x.date:ddMMyyyy}",
                    // ...
                    // the rest of the properties
                    // or selected
                })
                .ToList();
        }

example of how are the dates writen into json file:

File.WriteAllText("../../../dates.json", $"{{\n\t\"date\": \"{DateTime.Now:ddMMyyyy}\"\n}}");

enter image description here

spzvtbg
  • 964
  • 5
  • 13