From: Kai Moritz Date: Mon, 21 Dec 2015 21:50:33 +0000 (+0100) Subject: Implemented a LocalDate-to-Date converter X-Git-Tag: jpa-converters-1.0.0~25 X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=5a509f59870c94e679a587cd9c42552c39dc6bf0;p=jpa-converters Implemented a LocalDate-to-Date converter --- diff --git a/src/main/java/de/juplo/jpa/converters/LocalDateConverter.java b/src/main/java/de/juplo/jpa/converters/LocalDateConverter.java new file mode 100644 index 0000000..d6a5c51 --- /dev/null +++ b/src/main/java/de/juplo/jpa/converters/LocalDateConverter.java @@ -0,0 +1,39 @@ +package de.juplo.jpa.converters; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneOffset; +import java.util.Date; +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + + +/** + * Converts a {@link LocalDate} to a {@link Date}, by converting it into + * an {@Instant} for the GMT-timezone at {@link LocalTime.MIDNIGHT} and then + * convering that {@link Instant} into a {@link Date} as suggested in the + * official Java 8 Time tutorial. + *

+ * The {@link Date} can then be persisted as + * {@link java.persistene.TemporalType.DATE} with the help of the + * {@link java.persist.Tmporal}-annotation. + * @see https://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html + * @author Kai Moritz + */ +@Converter(autoApply = true) +public class LocalDateConverter implements AttributeConverter +{ + @Override + public Date convertToDatabaseColumn(LocalDate ld) + { + return Date.from(LocalDateTime.of(ld, LocalTime.MIDNIGHT).toInstant(ZoneOffset.UTC)); + } + + @Override + public LocalDate convertToEntityAttribute(Date date) + { + return LocalDate.from(date.toInstant()); + } +}