【问题标题】:CsvHelper changing how dates and times are outputCsvHelper 更改日期和时间的输出方式
【发布时间】:2016-09-19 02:31:46
【问题描述】:

我正在使用CsvHelper 编写一些 CSV 文件,并希望将我的日期和时间的格式更改为特定的格式。按照https://stackoverflow.com/a/31817621/223742 的建议,我可以成功地为我的每个班级创建地图。

但是它有一个明显的缺点,我现在需要为我想要导出的所有类创建自定义映射。因为我总是希望导出所有字段,这成为维护的噩梦,因为我每次都必须修改地图。

那么有什么简单的方法可以告诉 CsvHelper 使用特定格式编写所有日期和时间

【问题讨论】:

    标签: c# .net csvhelper


    【解决方案1】:

    使用较新版本 (12.1.2) 的 CsvHelper,可以使用 TypeConverterOptionsCache 归档它

    var options = new TypeConverterOptions { Formats = new[] { "MM/dd/yyyy" } };
    csvWriter.Context.TypeConverterOptionsCache.AddOptions<DateTime>(options);
    

    输出日期

    08/24/1991
    

    版本 20 将 TypeConverterOptionsCacheConfiguration 移至 Context。所以上面变成了

    var options = new TypeConverterOptions { Formats = new[] { "MM/dd/yyyy" } };
    csvWriter.Context.TypeConverterOptionsCache.AddOptions<DateTime>(options);
    csvWriter.Context.TypeConverterOptionsCache.AddOptions<DateTime?>(options);
    

    【讨论】:

    • 如果您同时拥有DateTimeDateTime?,请不要忘记注册这两种类型!
    • 在 Linux 上获取 error CS1545: Property, indexer, or event 'CsvContext.TypeConverterOptionsCache' is not supported by the language; try directly calling accessor methods 'CsvContext.get_TypeConverterOptionsCache()' or 'CsvContext.set_TypeConverterOptionsCache(?)'
    • 对于 CsvHelper 26.0.1,这是正确的答案。
    【解决方案2】:

    您可以使用 TypeConverterOptionsFactory 为每个类型全局设置它。

    void Main()
    {
        using (var stream = new MemoryStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        using (var csv = new CsvWriter(writer))
        {
            var options = new TypeConverterOptions
            {
                Format = "o"
            };
            TypeConverterOptionsFactory.AddOptions<DateTime>(options);
    
            csv.WriteField(DateTime.Now);
            csv.NextRecord();
            writer.Flush();
            stream.Position = 0;
    
            reader.ReadToEnd().Dump();
        }
    }
    

    输出:

    2016-09-19T11:01:41.5507054-05:00
    

    【讨论】:

    • TypeConverterOptionsFactory 在版本 26.0.1 中不再可见
    【解决方案3】:

    对我来说,在类上使用 CsvHelper 属性更容易。

    [Format("yyyy-MM-dd")] 完成了日期时间格式化的工作。

    namespace BarNamespace
    {
        using System;
        using CsvHelper.Configuration.Attributes;
    
        public class Foo
        {
            [Name("ColumnName1")]
            [Format("yyyy-MM-dd")]
            public DateTime Date { get; set; }
    
            [Name("ColumnName2")]
            public string Col2{ get; set; }
    
            [Name("ColumnName3")]
            public long Col3{ get; set; }
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-08
      • 2012-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多