Mapstruct LocalDateTime到即时

Bat*_*han 3 datetime-conversion java-time mapstruct localdate java.time.instant

我是Mapstruct的新手。我有一个包含LocalDateTime类型字段的模型对象。DTO包含Instant类型字段。我想将LocalDateTime类型字段映射到Instant类型字段。我有传入请求的TimeZone实例。

像这样手动设置字段;

set( LocalDateTime.ofInstant(x.getStartDate(), timeZone.toZoneId()) )
Run Code Online (Sandbox Code Playgroud)

如何使用Mapstruct映射这些字段?

Fil*_*lip 5

您有2种选择来实现所需的功能。

第一种选择:

使用@Context1.2.0.Final中的新注释作为timeZone属性,并定义自己的方法来执行映射。就像是:

public interface MyMapper {

    @Mapping(target = "start", source = "startDate")
    Target map(Source source, @Context TimeZone timeZone);

    default LocalDateTime fromInstant(Instant instant, @Context TimeZone timeZone) {
        return instant == null ? null : LocalDateTime.ofInstant(instant, timeZone.toZoneId());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,MapStruct将使用提供的方法在Instant和之间执行映射LocalDateTime

第二种选择:

public interface MyMapper {

    @Mapping(target = "start", expression = "java(LocalDateTime.ofInstant(source.getStartDate(), timezone.toZoneId()))")
    Target map(Source source, TimeZone timeZone);
}
Run Code Online (Sandbox Code Playgroud)

我个人的选择是使用第一个