You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSVHelper在.NET Framework 4.8中设置日期格式yyyy-MM-dd失效,但替换分隔符后生效的异常问题求助

CSVHelper在.NET Framework 4.8中设置日期格式yyyy-MM-dd失效,但替换分隔符后生效的异常问题求助

各位大佬,我碰到一个特别诡异的CSVHelper日期格式设置问题,折腾半天没搞明白根源,来请教大家!

事情是这样的:

  • 之前在.NET Core 7.0(C# v11,CSVHelper v30.0.1)的项目里,我要给CSVWriter生成的CSV文件统一设置日期格式,做法是在Map类里、调用Automap之前加上这段代码:
// Add default format for nullable and non-nullable dates
var csvContext = new CsvContext(new CsvConfiguration(CultureInfo.InvariantCulture));
csvContext.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "yyyy-MM-dd" };
csvContext.TypeConverterOptionsCache.GetOptions<DateTime?>().Formats = new[] { "yyyy-MM-dd" };

这样生成的日期就是我想要的2016-03-22格式,完全没问题。

  • 但最近在.NET Framework 4.8的项目里(试了CSVHelper v34和v30.0.1两个版本),同样的写法却出了怪事:
    • 如果设置格式字符串为yyyy-MM-dd,完全不生效,输出还是原始的日期格式(比如3/22/1972);
    • 可要是把格式里的减号换成其他符号,比如yyyy=MM-dd或者yyyy#MM-dd,反而能成功应用格式,只是输出的内容不是我要的(比如2016=03-22)。

我写了一个最小复现示例,代码如下:

public static void Main()
{
    var fileBytes = Array.Empty<byte>();
    var data = new List<Foo> {
        new Foo{Id=987654, Name="Smith, John", Birthdate=DateTime.Parse("3/22/1972"),EntryDate=DateTime.Parse("8/26/2024") },
        new Foo{Id=654321, Name="Doe, Jane", Birthdate=DateTime.Parse("8/29/1963"),EntryDate=DateTime.Parse("8/26/2024") }
    };
    var csvConfiguration = new CsvConfiguration(CultureInfo.CurrentCulture);

    using (var memoryStream = new MemoryStream())
    {
        using (var streamWriter = new StreamWriter(memoryStream))
        {
            using (var csvWriter = new CsvWriter(streamWriter, csvConfiguration))
            {
                csvWriter.Context.RegisterClassMap(new FooMap());
                csvWriter.WriteRecords(data);
            }
        }
        fileBytes = memoryStream.ToArray();
    }
    HttpContext current = HttpContext.Current;
    current.Trace.IsEnabled = false;
    current.Response.Clear();
    current.Response.ContentType = "application/octet-stream"; // or application/force-download
    current.Response.AddHeader("content-disposition", "attachment;    filename=SelectedRecords.csv");
    current.Response.BinaryWrite(fileBytes);
    current.Response.End();

}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime? Birthdate { get; set; }
    public DateTime? WithdrawDate { get; set; }
    public DateTime? EntryDate { get; set; }
}

public class FooMap : ClassMap<Foo>
    {
        public FooMap()
        {
            var csvContext = new CsvContext(new CsvConfiguration(CultureInfo.InvariantCulture));
// Works: the undesired format is successfully applied
// Comment these two lines out and uncomment the following lines.
// The output is '3/22/1972' - the original value with no addt'l formatting                
csvContext.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "yyyy#MM-dd" };
            csvContext.TypeConverterOptionsCache.GetOptions<DateTime?>().Formats = new[] { "yyyy#MM-dd" };
            //csvContext.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { "yyyy-MM-dd" };
            //csvContext.TypeConverterOptionsCache.GetOptions<DateTime?>().Formats = new[] { "yyyy-MM-dd" };

            AutoMap(csvContext);
        }
    }

注:我最终需要的是yyyy-MM-dd格式的纯日期,不是标准格式字符串"o"。

备注:内容来源于stack exchange,提问作者JimC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 03:42:58