Skip to content

Instantly share code, notes, and snippets.

@moelholm
Last active November 5, 2016 12:10
Show Gist options
  • Save moelholm/c657ed802c61febe6597ddbb59ca7553 to your computer and use it in GitHub Desktop.
Save moelholm/c657ed802c61febe6597ddbb59ca7553 to your computer and use it in GitHub Desktop.
Failed attempt: JPA attribute converter to "force" dates into UTC when writing to the database (and reading again)
/**
* Failed experiment: Attempting to force datetimes to be written/loaded using the UTC time zone.
*
*
* Good: OffsetDateTime is successfully converted into a "normal" Temporal data type ( here Calendar ) - resulting in Timestamp DDL etc.
*
* Bad : Datetimes are still stored using the JVM default time zone. ( In my part of the world: UTC+1 right now )
*
* The working solution I can come up with right now is setting the entire JVM into the UTC time zone. That surely does the job: Datetimes
* in the database show up as UTC versions.
*
* But setting the JVM into UTC seems like a crude solution to the problem at hand. Also note: I don't look for a driver specific solution.
* So no "timestamp with timezone" solution.
*
*/
@Converter(autoApply = true)
public class OffsetDateTimeConverter implements AttributeConverter<OffsetDateTime, Calendar> {
private final static ZoneId TIME_ZONE = ZoneId.of("UTC");
@Override
public Calendar convertToDatabaseColumn(OffsetDateTime offsetDateTime) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(TIME_ZONE));
// ( ^^ notice that the Calendar is created for a specific TimeZone ^^ )
// ( this is my apparently naive attempt at "forcing" the time to be converted to UTC before being sent to the db )
calendar.setTime(Date.from(offsetDateTime.toInstant()));
return calendar;
}
@Override
public OffsetDateTime convertToEntityAttribute(Calendar dbData) {
Instant instant = dbData.toInstant();
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(instant, TIME_ZONE);
return offsetDateTime;
}
}
@moelholm
Copy link
Author

moelholm commented Nov 5, 2016

By the way: OffsetDateTime ... just happens to be what I like to use in my entities ;)

( by the way @thanssen : I did read your excellent post on using the hibernate8 library ... that works great ;) ... but I wanted to additionally ensure the UTC conversion ;) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment