Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;

}

like image 851
Hemant Avatar asked Jan 17 '26 23:01

Hemant


1 Answers

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

@PostConstruct
public void setTimeZone() {
   TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
}
like image 57
Jitendra Tak Avatar answered Jan 20 '26 13:01

Jitendra Tak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!