Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper configuration to use local time for all DateTime properties

Say I have 2 classes with the same set of properties:

public class MyDto
{
    public int Id { get; set; }
    public DateTime CreatedOn { get; set; }
}

public class MyViewModel
{
    public int Id { get; set; }
    public DateTime CreatedOn { get; set; }
}

I want to map with AutoMapper, adjusting the UTC date of the input class to local time of the output class, e.g., granted I am in UK where UTC offset currently is 1h:

var input = new MyDto {Id = 1, CreatedOn = DateTime.Parse("01-01-2015 14:30")};
var output = Mapper.Map<MyViewModel>(input); // output.CreatedOn = "01-01-2015 15:30"

Can I cofigure AutoMapper to this automatically for all DateTime properties?

N.B. to adjust the time I use DateTime.SpecifyKind(value, DateTimeKind.Utc)

like image 400
Ruslan Avatar asked May 09 '15 14:05

Ruslan


1 Answers

You can create a custom type converter:

public class CustomDateTimeConverter : ITypeConverter<DateTime, DateTime> {
    public DateTime Convert(ResolutionContext context) {
        var inputDate = (DateTime) context.SourceValue;
        var timeInUtc = DateTime.SpecifyKind(inputDate, DateTimeKind.Utc);
        return TimeZoneInfo.ConvertTime(timeInUtc, TimeZoneInfo.Local);
    }
}

This will make AutoMapper perform the conversion from UTC to local time for every mapping between two DateTime properties.

like image 190
Thiago Sá Avatar answered Nov 18 '22 20:11

Thiago Sá