我正在使用MySQL,hibernate / JPA和spring boot。我从前端接收的数据是正确的,即使在后端也是完全正确的,但是当我将其保存到数据库时,它节省了-2个小时。所以当上传时间是
2019-08-07 00:00然后在数据库中另存为:2019-08-06 22:00
@Entity
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(unique = true)
private String name;
private String title;
private String description;
@JsonIgnore
@Column(name = "resource_path")
private String resourcePath;
@Column(name = "upload_datetime", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date uploadDatetime;
@Column(name = "approval_end_time", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date approvalEndTime;
@Column(name = "active_start_time", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date activeStartTime;
@Column(name = "active_end_time", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date activeEndTime;
@OneToMany(mappedBy = "document", cascade= CascadeType.ALL, orphanRemoval = true)
private Set<UsersDocuments> documentsForUsers = new HashSet<>();
@ManyToOne
@JoinColumn(name="user_id")
private User user;
Document document = new Document(title, desc);
document.setUploadDatetime(new Date());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(document.getUploadDatetime());
System.out.println("ULOAD " + strDate); // writes 2019-08-07 01:07:57, but saves -2h to db
try {
document.setApprovalEndTime(new Date());
document.setActiveStartTime(formatter.parse(startOfReading));
document.setActiveEndTime(formatter.parse(endOfReading));
} catch (ParseException e){
}
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
最佳答案
尝试在格式化程序中设置时区。
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
dateFormat.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
关于java - 在应用程序中可以确定日期,但可以将数据库保存为-2小时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57393387/