30ab6bb3e62b5a53a7363b46b1138ee707b478d3
[JavaForFun] /
1 package de.spring.example.persistence.converters;
2
3 import java.sql.Timestamp;
4 import java.time.LocalDateTime;
5 import java.time.OffsetDateTime;
6 import java.time.ZoneId;
7 import java.time.ZonedDateTime;
8
9 import javax.persistence.AttributeConverter;
10 import javax.persistence.Converter;
11
12 @Converter(autoApply = true)
13 public class OffsetDateTimeAttributeConverter implements AttributeConverter<OffsetDateTime, Timestamp> {
14
15         @Override
16         public Timestamp convertToDatabaseColumn(OffsetDateTime offsetDateTime) {
17                 Timestamp timestamp = null;
18                 
19                 if (offsetDateTime != null) {
20                         timestamp = Timestamp.valueOf(offsetDateTime.toLocalDateTime());
21                 }
22                 
23                 return timestamp;
24         }
25
26         @Override
27         public OffsetDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
28                 OffsetDateTime offsetDateTime = null;
29                 
30                 if (sqlTimestamp != null) {
31                         final LocalDateTime localDateTime = sqlTimestamp.toLocalDateTime();
32                         final ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
33                         offsetDateTime = zonedDateTime.toOffsetDateTime();
34                 }
35                 
36                 return offsetDateTime;
37         }
38
39 }