Skip to content

Instantly share code, notes, and snippets.

@elviejokike
Last active August 2, 2023 11:16
Show Gist options
  • Save elviejokike/47e18e0836a86fb789e7c00b69e22847 to your computer and use it in GitHub Desktop.
Save elviejokike/47e18e0836a86fb789e7c00b69e22847 to your computer and use it in GitHub Desktop.
ZonedDateTime Attribute Converter - Database timestamps stored in UTC. JPA model uses the default time zone of the system.
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Timestamp;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@Converter(autoApply = true)
public class ZonedDateTimeAttributeConverter implements AttributeConverter<ZonedDateTime, Timestamp> {
static ZoneId utcZoneId = ZoneId.of("UTC");
static ZoneId defaultZoneId = ZoneId.systemDefault();
@Override
public Timestamp convertToDatabaseColumn(ZonedDateTime zonedDateTime) {
// Store always in UTC
return (zonedDateTime == null ? null :
Timestamp.valueOf(toUtcZoneId(zonedDateTime).toLocalDateTime()));
}
@Override
public ZonedDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
// Read from database (stored in UTC) and return with the system default.
return (sqlTimestamp == null ? null :
toDefaultZoneId(sqlTimestamp.toLocalDateTime().atZone(ZoneId.of("UTC"))));
}
private ZonedDateTime toUtcZoneId(ZonedDateTime zonedDateTime){
return zonedDateTime.withZoneSameInstant(utcZoneId);
}
private ZonedDateTime toDefaultZoneId(ZonedDateTime zonedDateTime){
return zonedDateTime.withZoneSameInstant(defaultZoneId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment