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

2

8

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!

Blanket answered 29/11, 2019 at 1:6 Comment(0)
J
17

Add the following line to the application.properties file:

spring.jackson.deserialization.ADJUST_DATES_TO_CONTEXT_TIME_ZONE = false

References:

Jerrome answered 29/11, 2019 at 3:48 Comment(1)
Can I disable this only for one field?Walrus
T
7

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);
Titleholder answered 16/4, 2021 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.