From: Kai Moritz Date: Mon, 21 Dec 2015 23:14:34 +0000 (+0100) Subject: Implemented a OffsetTime-to-GregorianCalendar converter X-Git-Tag: jpa-converters-1.0.0~18 X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=1379e18f0fc5e125fef994556e30a4356a08ba82;p=jpa-converters Implemented a OffsetTime-to-GregorianCalendar converter --- diff --git a/src/main/java/de/juplo/jpa/converters/OffsetTimeConverter.java b/src/main/java/de/juplo/jpa/converters/OffsetTimeConverter.java new file mode 100644 index 0000000..4543950 --- /dev/null +++ b/src/main/java/de/juplo/jpa/converters/OffsetTimeConverter.java @@ -0,0 +1,43 @@ +package de.juplo.jpa.converters; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.OffsetTime; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.GregorianCalendar; +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + + +/** + * Converts an {@link OffsetTime} to a {@link GregorianCalendar}, by converting + * it into a {@ZonedDateTime} at the date of {@link Instant.EPOCH} and + * then convering that {@link ZonedDateTime} into a {@link GregorianCalendar} + * as suggested in the official Java 8 Time tutorial. + *

+ * The {@link GregorianCalendar} can then be persisted as + * {@link java.persistene.TemporalType.TIME} with the help of the + * {@link java.persist.Tmporal}-annotation. + * @see https://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html + * @author Kai Moritz + */ +@Converter(autoApply = true) +public class OffsetTimeConverter implements AttributeConverter +{ + private final static LocalDate EPOCH = LocalDate.from(Instant.EPOCH); + + + @Override + public GregorianCalendar convertToDatabaseColumn(OffsetTime ot) + { + ZoneOffset offset = ot.getOffset(); + return GregorianCalendar.from(ZonedDateTime.of(EPOCH, ot.toLocalTime(), offset)); + } + + @Override + public OffsetTime convertToEntityAttribute(GregorianCalendar calendar) + { + return OffsetTime.from(calendar.toInstant()); + } +}