Implemented an OffsetDateTime-to-GregorianCalendar converter
[jpa-converters] / src / main / java / de / juplo / jpa / converters / OffsetDateTimeConverter.java
1 package de.juplo.jpa.converters;
2
3 import java.time.OffsetDateTime;
4 import java.time.ZonedDateTime;
5 import java.util.GregorianCalendar;
6 import javax.persistence.AttributeConverter;
7 import javax.persistence.Converter;
8
9
10 /**
11  * Converts a {@link OffsetDateTime} to a {@link GregorianCalendar}, by first
12  * converting it into a {@link ZonedDateTime} and then converting it as
13  * suggested in the official Java 8 Time tutorial.
14  * <p>
15  * The {@link GregorianCalendar} can then be persisted as
16  * {@link java.persistene.TemporalType.TIMESTAMP} with the help of the
17  * {@link java.persist.Tmporal}-annotation.
18  * @see https://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html
19  * @author Kai Moritz
20  */
21 @Converter(autoApply = true)
22 public class OffsetDateTimeConverter implements AttributeConverter<OffsetDateTime, GregorianCalendar>
23 {
24   @Override
25   public GregorianCalendar convertToDatabaseColumn(OffsetDateTime odt)
26   {
27     return GregorianCalendar.from(ZonedDateTime.from(odt));
28   }
29
30   @Override
31   public OffsetDateTime convertToEntityAttribute(GregorianCalendar calendar)
32   {
33     return OffsetDateTime.from(calendar.toZonedDateTime());
34   }
35 }