Skip to content

Instantly share code, notes, and snippets.

@asgeirn
Created January 10, 2025 15:24
Show Gist options
  • Save asgeirn/81bb2f246960c0a3242c694d45cdf3e0 to your computer and use it in GitHub Desktop.
Save asgeirn/81bb2f246960c0a3242c694d45cdf3e0 to your computer and use it in GitHub Desktop.
Jackson Dates with Time Zones
package org.wildfly.quickstarts.helloworld;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.junit.Test;
import java.io.IOException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import static junit.framework.TestCase.assertEquals;
/* You need the following dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
*/
public class JacksonDatesWithTimeZones {
@Test
public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect()
throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
String converted = objectMapper.writeValueAsString(now);
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
System.out.println("input: " + now);
System.out.println("serialized: " + converted);
System.out.println("restored: " + restored);
assertEquals(now, restored);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment