60019f5b242aa28aeadae17c25db6664fa7e4272
[jpa-converters] / src / main / java / de / juplo / jpa / converters / LocalTimeConverter.java
1 package de.juplo.jpa.converters;
2
3 import java.time.Instant;
4 import java.time.LocalDate;
5 import java.time.LocalDateTime;
6 import java.time.LocalTime;
7 import java.time.ZoneOffset;
8 import java.util.Date;
9 import javax.persistence.AttributeConverter;
10 import javax.persistence.Converter;
11
12
13 /**
14  * Converts a {@link LocalTime} to a {@link Date}, by converting it into
15  * an {@Instant} for the GMT-timezone at the date of {@link Instant.EPOCH} and
16  * then convering that {@link Instant} into a {@link Date} as suggested in the
17  * official Java 8 Time tutorial.
18  * <p>
19  * The {@link Date} 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 LocalTimeConverter implements AttributeConverter<LocalTime, Date>
27 {
28   private final static LocalDate EPOCH = LocalDate.from(Instant.EPOCH);
29
30
31   @Override
32   public Date convertToDatabaseColumn(LocalTime lt)
33   {
34     return Date.from(LocalDateTime.of(EPOCH, lt).toInstant(ZoneOffset.UTC));
35   }
36
37   @Override
38   public LocalTime convertToEntityAttribute(Date date)
39   {
40     return LocalTime.from(date.toInstant());
41   }
42 }