Java 日期在应用程序中可以,但在数据库中保存时间为-2小时

Java 日期在应用程序中可以,但在数据库中保存时间为-2小时,java,mysql,spring,hibernate,jpa,Java,Mysql,Spring,Hibernate,Jpa,我正在使用MySQL、hibernate/JPA和SpringBoot。我从前端接收到的数据是正确的,即使在我的后端也是完全正确的,但当我将其保存到数据库时,它只保存了-2小时。所以当上传时间是 2019-08-07 00:00然后在数据库中保存为:2019-08-06 22:00 @Entity public class Document { @Id @GeneratedValue(strategy = GenerationType.AUTO) private lon

我正在使用MySQL、hibernate/JPA和SpringBoot。我从前端接收到的数据是正确的,即使在我的后端也是完全正确的,但当我将其保存到数据库时,它只保存了-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"));

这里有许多活动部件,但其核心是MySQL将在内部存储数据,通常使用UTC格式,这取决于所使用的引擎。当客户端应用程序或数据库查询工具连接时,它要么通过连接字符串声明其时区,要么接受运行db的服务器的默认值。最有可能的是,你的应用程序或客户端正在声明时区,而另一个则没有,这就解释了为什么数据看起来不同


查看jdbc字符串上的useTimezone和serverTimezone连接参数或MySQL客户端的设置。

您的sql版本是什么?JPA以UTC存储日期等。应用程序中的时间在当前或服务器时区中。