How to save timestamp in UTC format for Audit fields @CreatedDate, @LastModifiedDate in Spring JPA

大憨熊 提交于 2021-01-05 12:26:52

问题


This is my Base Class for Entities with audit fields. For fields @CreatedDate, @LastModifiedDate, by default it is saving my system time. My requirement is to save timestamp in UTC.

Does anyone have a solution of this?

import java.time.LocalDateTime;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import lombok.Data;


@MappedSuperclass
@Data
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {

    @LastModifiedDate
    @Column(name="last_modified_datetime")
    private LocalDateTime lastModifiedDateTime;

    @CreatedDate
    @Column(name="created_datetime")
    private LocalDateTime createdDateTime;

}


回答1:


This is problem of time zone. use this code for spring boot.

@PostConstruct
public void setTimeZone() {
   TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
}


来源:https://stackoverflow.com/questions/60073200/how-to-save-timestamp-in-utc-format-for-audit-fields-createddate-lastmodified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!