Implemented a OffsetTime-to-GregorianCalendar converter
authorKai Moritz <kai@juplo.de>
Mon, 21 Dec 2015 23:14:34 +0000 (00:14 +0100)
committerKai Moritz <kai@juplo.de>
Tue, 15 Aug 2017 17:44:40 +0000 (19:44 +0200)
src/main/java/de/juplo/jpa/converters/OffsetTimeConverter.java [new file with mode: 0644]

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 (file)
index 0000000..4543950
--- /dev/null
@@ -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.
+ * <p>
+ * 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<OffsetTime, GregorianCalendar>
+{
+  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());
+  }
+}