Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# AutoMapper to convert DateTime UTC to Local

I use ASP.NET with WebApi's(Rest) and AngularJS. If I send DateTime objects from Client (Angular) to Server (C#) I recieve distorted (-2 hours) Dates because of the timezone. So I decided to use Automapper.

My current code looks like this:

AutoMapperConfiguration.cs:

public class AutoMapperConfiguration
{
    public void Configure()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<DateTime, DateTime>().ConvertUsing<UtcToLocalConverter>();
        });
    }
}

UtcToLocalConverter.cs:

public class UtcToLocalConverter : AutoMapper.ITypeConverter<DateTime, DateTime>
{
    public DateTime Convert(DateTime source, DateTime destination, ResolutionContext context)
    {
        var inputDate = source;
        if (inputDate.Kind == DateTimeKind.Utc)
        {
            return inputDate.ToLocalTime();
        }
        return inputDate;
    }
}

Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        new AutoMapperConfiguration().Configure();
        //...some more stuff...
    }
}

I want to have all objects of type DateTime which I recieve from Client automatically converted but this is not happening with this piece of code. What did I wrong? Can someone help me resolving this Problem?

Thanks in advance.

like image 601
H. Senkaya Avatar asked Oct 15 '25 03:10

H. Senkaya


1 Answers

I have noticed a change with AutoMapper after updating from an old version (I was on a very old one).Even with map configurations for DateTimes, objects mapped from AutoMapper end up converting the date to UTC time after the Convert method from the custom converter. A look into the release notes may help here. I have not found an option to prevent this from happening.

Also, check if your configuration settings are being used.

Do you need to call initialize after creating the configuration object?

AutoMapper.Mapper.Initialize(cfg);

so...

public void Configure()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<DateTime, DateTime>().ConvertUsing<UtcToLocalConverter>();
    });
    AutoMapper.Mapper.Initialize(cfg);
}
like image 192
thenninger Avatar answered Oct 18 '25 06:10

thenninger



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!