简体   繁体   中英

Timezone of ZonedDateTime changed to UTC during auto conversion of RequestBody with Spring Boot

I'm trying to keep ZoneId of ZonedDateTime which is set on front-end while performing POST/PUT to Spring Boot controller.

The value I want to transfer is: 2019-05-01T00:00:00+01:00[Europe/Zagreb]

After POST/PUT the ZoneId is converted to UTC and hours are adjusted. Technically this updated value represents the same point on time line, but the original ZoneId is lost and I would like to have it stored to be able to show it back later to end user.

// DTO
public class PriceInfoDTO {
    @JsonFormat( pattern = "yyyy-MM-dd'T'HH:mm:ssXXX['['VV']']", 
        with = JsonFormat.Feature.WRITE_DATES_WITH_ZONE_ID )
    @DateTimeFormat( pattern = "yyyy-MM-dd'T'HH:mm:ssXXX['['VV']']", iso = ISO.DATE_TIME )
    private ZonedDateTime validFrom;
}


// Controller
@PutMapping(
    path = PATH + "/{id}",
    consumes = MediaType.APPLICATION_JSON_VALUE,
    produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<PriceInfo> update(
    @PathVariable("id") final Integer id,
    @RequestBody final PriceInfoDTO dto
) {
    System.out.println(dto);
    ...
}

Looking at Network tab in my browser, the request from browser to Spring Controller has this value (payload):

2019-05-01T00:00:00+01:00[Europe/Zagreb]

which is the same as format pattern.

When I dump DTO to console, I get this result:

2019-04-30T22:00Z[UTC]

Is there any way to preserve ZoneId as it was received in a request? Should I write my own Serializer and Deserializer to achieve this?

Thanks!

Add the following line to the application.properties file:

spring.jackson.deserialization.ADJUST_DATES_TO_CONTEXT_TIME_ZONE = false

References:

Can also be set programmatically with ObjectMapper :

objectMapper.configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, true);
objectMapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM