X-Git-Url: https://juplo.de/gitweb/?a=blobdiff_plain;f=src%2Fmain%2Fjava%2Fde%2Fjuplo%2Fjpa%2Fconverters%2FOffsetTimeConverter.java;fp=src%2Fmain%2Fjava%2Fde%2Fjuplo%2Fjpa%2Fconverters%2FOffsetTimeConverter.java;h=4543950c149c3737acb9013b4559dc698736cb5d;hb=1379e18f0fc5e125fef994556e30a4356a08ba82;hp=0000000000000000000000000000000000000000;hpb=a4526e622738d2360f2cd79407cfa3f8d406fa10;p=jpa-converters 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()); + } +}