AutoMapper configuration to use local time for all DateTime properties

Let's 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 match AutoMapper by adjusting the UTC date of the input class to the local time of the output class, for example, provided by I in the UK, where the UTC offset is currently 1 hour:

 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 automatically configure AutoMapper for all DateTime properties?

NB for setting the time I use DateTime.SpecifyKind(value, DateTimeKind.Utc)

+6
source share
1 answer

You can create a custom converter type:

 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 force AutoMapper to convert from UTC to local time for each mapping between the two DateTime properties.

+3
source

Source: https://habr.com/ru/post/986870/


All Articles