Created
June 15, 2017 07:59
-
-
Save elviejokike/fd361aed7b8d7032991990ccbbe5186c to your computer and use it in GitHub Desktop.
ZonedDateTime Attribute Converter - UTC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.philips.research.pathis.slideanalysis.domain.entity; | |
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