【问题标题】:Format date and Filter by range格式化日期并按范围过滤
【发布时间】:2020-09-15 13:37:58
【问题描述】:

您好,我正在尝试格式化日期

  • CSV 格式为dd / mm / yyyy
  • 并且需要将 ddmmyyyy 放在 json 中
    • 按范围过滤,例如从0101201931012019

谁能给我一个建议?

序列化

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);
    }
}

型号

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; }
}

【问题讨论】:

  • JSON 日期的事实标准是 ISO8601 格式,即YYYY-MM-DD。没有理由使用需要每个客户都采用的自定义本地化格式
  • 无论如何,JSON.NET 允许您自定义日期的序列化方式。有几个关于这个的问题,like this one
  • filtered by a range example 01012019 until 31012019 字符串格式不允许允许按范围过滤。使用字典顺序比较字符串,01012019 总是在02011970 之前,因为日期元素的顺序相反。 ISO8601 格式允许排序和过滤,因为元素的顺序正确

标签: c# .net-core csvhelper


【解决方案1】:

这应该可行:

        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();
        }

日期如何写入 json 文件的示例:

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

【讨论】:

  • 不显示json中的数据。选择后显示字符串"x.date"ddMMyyyy"
  • 有没有你可能是空值而不是日期
猜你喜欢
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 2021-05-25
  • 2018-06-19
  • 1970-01-01
相关资源
最近更新 更多