DulcetAirman

JPA-Converter for OffsetDateTime

May 26th, 2015 (edited)
380
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. This stores timestamps, so there is no time zone in the database.
  3. It reads the timestamp and simply uses UTC.
  4. To get the local time use this:
  5. ZonedDateTime timeLocal = obj.getTimeXYZ().atZoneSameInstant(ZoneId.systemDefault());
  6. */
  7.  
  8. package XXXXXXXXXXXXXXXXXXXXXXXXXX;
  9.  
  10. import java.sql.Timestamp;
  11. import java.time.LocalDateTime;
  12. import java.time.OffsetDateTime;
  13. import java.time.ZoneId;
  14. import java.time.ZoneOffset;
  15.  
  16. import javax.persistence.AttributeConverter;
  17. import javax.persistence.Converter;
  18.  
  19. @Converter(autoApply = true)
  20. public class OffsetDateTimeConverter implements
  21.     AttributeConverter<OffsetDateTime, Timestamp> {
  22.   @Override
  23.   public Timestamp convertToDatabaseColumn(final OffsetDateTime entityValue) {
  24.     if (entityValue == null) {
  25.       return null;
  26.     }
  27.     return Timestamp.valueOf(entityValue.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());
  28.   }
  29.  
  30.   @Override
  31.   public OffsetDateTime convertToEntityAttribute(final Timestamp databaseValue) {
  32.     if (databaseValue == null) {
  33.       return null;
  34.     }
  35.     final LocalDateTime localDateTime = databaseValue.toLocalDateTime();
  36.     final ZoneOffset offset = ZoneId.of("UTC").getRules()
  37.         .getOffset(localDateTime);
  38.     return OffsetDateTime.of(localDateTime, offset);
  39.   }
  40. }
RAW Paste Data Copied