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