java - 日期在应用程序中没问题,但在数据库中保存了 -2 小时

标签 java mysql spring hibernate jpa

我正在使用 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/

相关文章:

java - Ehcache put 添加到堆上失败

spring - Spring Boot session 超时不起作用?

mysql - 带有 mysql 问题的 Rails 3

Java:将分数插入远程 MySQL 数据库而无需硬编码登录凭据

java - 拆分 Java Spring

spring - 元素 <cache> 不允许属性 "maxBytesLocalDisk"

java - Double 的 Eclipse 错误

java - SAXParseException 本地化

java - 线程完成后触发 System.exit()

java - 将消息从服​​务器发送到 Android 应用程序