Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# automapper format datetime to iso string

Tags:

c#

automapper

When Automapper converts a DateTime that is cast to an object to a string, it uses the ToString() method which returns a string in a format defined by the culture. How do I configure it so that it always maps to ISO string?

        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"]);

The first assertion is fine, but the second fails:

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"
  -----------^
like image 696
Bart van den Burg Avatar asked Oct 14 '25 07:10

Bart van den Burg


1 Answers

Here is an example how you can do this:

Example models:

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

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

Code snippet:

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

Code Snippet #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();
}
like image 58
MaKCbIMKo Avatar answered Oct 18 '25 05:10

MaKCbIMKo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!