C# 自动映射器将日期时间格式化为 iso 字符串

本文关键字:格式化 时间 iso 字符串 日期 映射 | 更新日期: 2023-09-27 17:55:25

当自动映射器将强制转换为对象的 DateTime 转换为字符串时,它使用 ToString() 方法,该方法以区域性定义的格式返回字符串。如何配置它,使其始终映射到 ISO 字符串?

        var data = new Dictionary<string, object>
        {
            { "test", new DateTime(2016, 7, 6, 9, 33, 0) }
        };
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<DateTime, string>().ConvertUsing(dt => dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
        });
        var mapper = config.CreateMapper();
        Assert.AreEqual("2016-07-06T07:33:00Z", mapper.Map<string>(data["test"]));
        Assert.AreEqual("2016-07-06T07:33:00Z", mapper.Map<IDictionary<string, string>>(data)["test"]);

第一个断言很好,但第二个断言失败:

Result Message: 
Expected string length 20 but was 17. Strings differ at index 0.
  Expected: "2016-07-06T07:33:00Z"
  But was:  "6-7-2016 09:33:00"
  -----------^

C# 自动映射器将日期时间格式化为 iso 字符串

下面是如何执行此操作的示例:

示例模型:

class A
{
    public DateTime DateTime { get; set; }
}
class B
{
    public string DateTime { get; set; } 
}

代码片段:

static void Main()
{
    var config = new MapperConfiguration(
        cfg =>
            {
                cfg.CreateMap<A, B>();
                cfg.CreateMap<DateTime, string>().ConvertUsing(dt => dt.ToString("u"));
            });
    var mapper = config.CreateMapper();
    var a = new A();
    Console.WriteLine(a.DateTime); // will print DateTime.ToString
    Console.WriteLine(mapper.Map<B>(a).DateTime); // will print DateTime in ISO string
    Console.ReadKey();
}

代码片段 #2:

static void Main()
{
    var data = new Dictionary<string, DateTime> // here is main problem
    {
        { "test", new DateTime(2016, 7, 6, 9, 33, 0) }
    };
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<DateTime, string>().ConvertUsing(dt => dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
    });
    var mapper = config.CreateMapper();
    Console.WriteLine(mapper.Map<string>(data["test"]));
    Console.WriteLine(mapper.Map<IDictionary<string, string>>(data)["test"]);
    Console.ReadKey();
}