'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!
Solution 1:[1]
Add the following line to the application.properties file:
spring.jackson.deserialization.ADJUST_DATES_TO_CONTEXT_TIME_ZONE = false
References:
- Baeldung: Jackson Date: Deserialize Joda ZonedDateTime with Time Zone Preserved
- Javadoc: jackson-databind 2.6.0 API: ADJUST_DATES_TO_CONTEXT_TIME_ZONE
- Spring Boot: “How-to” Guides: Customize the Jackson ObjectMapper
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andreas |
| Solution 2 | Hugo P |
