Implemented a OffsetTime-to-GregorianCalendar converter
[jpa-converters] / src / main / java / de / juplo / jpa / converters / OffsetTimeConverter.java
1 package de.juplo.jpa.converters;
2
3 import java.time.Instant;
4 import java.time.LocalDate;
5 import java.time.OffsetTime;
6 import java.time.ZoneOffset;
7 import java.time.ZonedDateTime;
8 import java.util.GregorianCalendar;
9 import javax.persistence.AttributeConverter;
10 import javax.persistence.Converter;
11
12
13 /**
14  * Converts an {@link OffsetTime} to a {@link GregorianCalendar}, by converting
15  * it into a {@ZonedDateTime} at the date of {@link Instant.EPOCH} and
16  * then convering that {@link ZonedDateTime} into a {@link GregorianCalendar}
17  * as suggested in the official Java 8 Time tutorial.
18  * <p>
19  * The {@link GregorianCalendar} can then be persisted as
20  * {@link java.persistene.TemporalType.TIME} with the help of the
21  * {@link java.persist.Tmporal}-annotation.
22  * @see https://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html
23  * @author Kai Moritz
24  */
25 @Converter(autoApply = true)
26 public class OffsetTimeConverter implements AttributeConverter<OffsetTime, GregorianCalendar>
27 {
28   private final static LocalDate EPOCH = LocalDate.from(Instant.EPOCH);
29
30
31   @Override
32   public GregorianCalendar convertToDatabaseColumn(OffsetTime ot)
33   {
34     ZoneOffset offset = ot.getOffset();
35     return GregorianCalendar.from(ZonedDateTime.of(EPOCH, ot.toLocalTime(), offset));
36   }
37
38   @Override
39   public OffsetTime convertToEntityAttribute(GregorianCalendar calendar)
40   {
41     return OffsetTime.from(calendar.toInstant());
42   }
43 }