Search code examples
hibernatetimestamputchibernate-envers

How to save UTC (instead of local) timestamps for Hibernate Envers revision info?


Using Hibernate/Envers, how to:

  1. Save UTC (instead of local) timestamps for Hibernate Envers revision info?
  2. Get timestamps as a LocalDateTime (Java 8)?

Solution

  • 1) From the revision listener, call the fixTimezone method of the revision, as shown below.

    2) To get it as LocalDateTime use the getRevisionDate method, as shown below.

    public class MyRevisionListener
        implements RevisionListener {
    
        @Override
        public void newRevision(Object revisionEntity) {
            MyRevision revision = (MyRevision)revisionEntity;
            revision.fixTimezone();
            }
        }
    
    @Entity
    @RevisionEntity (MyRevisionListener.class)
    public class MyRevision
          implements Serializable {
    
        @Id
        @GeneratedValue
        @RevisionNumber
        private long id;
    
        @RevisionTimestamp
        @Temporal (TemporalType.TIMESTAMP)
        @Column (nullable = false)
        private Date date;
    
        private static final ZoneId ZONE_ID_UTC = ZoneId.of("UTC");
    
        public void fixTimezone() {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZONE_ID_UTC);
            date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            }
    
        @NotNull
        public LocalDateTime getRevisionDate() {
            return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
            }
    
        ...
        }
    

    Related Hibernate issues: