Mapstruct LocalDateTime to Instant

前端 未结 1 1203
南方客
南方客 2021-01-19 15:25

I am new in Mapstruct. I have a model object which includes LocalDateTime type field. DTO includes Instant type field. I want to map LocalDat

相关标签:
1条回答
  • 2021-01-19 15:51

    You have 2 options to achieve what you are looking for.

    First option:

    Use the new @Context annotation from 1.2.0.Final for the timeZone property and define your own method that would perform the mapping. Something like:

    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());
        }
    }
    

    MapStruct will then use the provided method to perform mapping between Instant and LocalDateTime.

    The second option:

    public interface MyMapper {
    
        @Mapping(target = "start", expression = "java(LocalDateTime.ofInstant(source.getStartDate(), timezone.toZoneId()))")
        Target map(Source source, TimeZone timeZone);
    }
    

    My personal option would be to use the first one

    0 讨论(0)
提交回复
热议问题