From: Kai Moritz Date: Mon, 21 Dec 2015 20:49:44 +0000 (+0100) Subject: Implemented a LocalDateTime-to-Date converter X-Git-Tag: jpa-converters-1.0.0~26 X-Git-Url: https://juplo.de/gitweb/?p=jpa-converters;a=commitdiff_plain;h=d05d2977dd2e2d90177bae7c84ab93d23282129b Implemented a LocalDateTime-to-Date converter --- diff --git a/src/main/java/de/juplo/jpa/converters/LocalDateTimeConverter.java b/src/main/java/de/juplo/jpa/converters/LocalDateTimeConverter.java new file mode 100644 index 0000000..0e5251d --- /dev/null +++ b/src/main/java/de/juplo/jpa/converters/LocalDateTimeConverter.java @@ -0,0 +1,36 @@ +package de.juplo.jpa.converters; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Date; +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + + +/** + * Converts a {@link LocalDateTime} to a {@link Date}, by converting it into + * an {@Instant} for the GMT-timezone 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.TIMESTAMP} 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 LocalDateTimeConverter implements AttributeConverter +{ + @Override + public Date convertToDatabaseColumn(LocalDateTime ldt) + { + return Date.from(ldt.toInstant(ZoneOffset.UTC)); + } + + @Override + public LocalDateTime convertToEntityAttribute(Date date) + { + return LocalDateTime.from(date.toInstant()); + } +}