I'm trying to convert an object using a mapper with Mapstruct that has a Date (java.util.Date) field to an object with a LocalDateTime field. The problem is that it maps the time wrong because in the object with the LocalDateTime field it always says 2 hours less.
@Mapping(source = "createdDate", target = "createdLocalDateTime")
ObjectA toEntity(ObjectB);
I think that the problem is the auto implementation:
if ( createdDate!= null ) {
objectA.createdLocalDateTime( LocalDateTime.ofInstant( createdDate.toInstant(), ZoneId.of( "UTC" ) ) );
}
How can I fix this? Thanks!
CodePudding user response:
A basic conversion would be
Date date= new Date();
LocalDateTime localdate= date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
Since you have not posted your conversion code we don't know what is going on your side.
CodePudding user response:
There is already a conversation about this on the mapstruct issues tracker. There they talk about losing a day, but the cause and solution are similar:
The solution that you can do and is super trivial is to provide you own way of mapping between Date to LocalDate.
e.g.
public class DateUtils {
public static LocalDate toLocalDate(Date date) {
return date == null ? null : date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
}
}
and make sure that DateUtils is part of Mapper#uses. This way MapStruct will use your custom function to map between Date and LocalDate.