/*
This stores timestamps, so there is no time zone in the database.
It reads the timestamp and simply uses UTC.
To get the local time use this:
ZonedDateTime timeLocal = obj.getTimeXYZ().atZoneSameInstant(ZoneId.systemDefault());
*/
package XXXXXXXXXXXXXXXXXXXXXXXXXX;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class OffsetDateTimeConverter implements
AttributeConverter<OffsetDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(final OffsetDateTime entityValue) {
if (entityValue == null) {
return null;
}
return Timestamp.valueOf(entityValue.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());
}
@Override
public OffsetDateTime convertToEntityAttribute(final Timestamp databaseValue) {
if (databaseValue == null) {
return null;
}
final LocalDateTime localDateTime = databaseValue.toLocalDateTime();
final ZoneOffset offset = ZoneId.of("UTC").getRules()
.getOffset(localDateTime);
return OffsetDateTime.of(localDateTime, offset);
}
}
Comments