Implemented a LocalDate-to-Date converter
[jpa-converters] / src / main / java / de / juplo / jpa / converters / LocalDateConverter.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 LocalDate} to a {@link Date}, by converting it into
15  * an {@Instant} for the GMT-timezone at {@link LocalTime.MIDNIGHT} and then
16  * 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.DATE} 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 LocalDateConverter implements AttributeConverter<LocalDate, Date>
27 {
28   @Override
29   public Date convertToDatabaseColumn(LocalDate ld)
30   {
31     return Date.from(LocalDateTime.of(ld, LocalTime.MIDNIGHT).toInstant(ZoneOffset.UTC));
32   }
33
34   @Override
35   public LocalDate convertToEntityAttribute(Date date)
36   {
37     return LocalDate.from(date.toInstant());
38   }
39 }