调用springboot rest API的时差

问题描述 投票:0回答:2

我在数据库表中存储的时间与其余的GET调用之间相差了一个小时。我不确定为什么会这样,因为我的数据库,REST Server和UI应用程序在同一时区运行。请帮助我。

Time stored in database : 2020-05-19
Time on REST GET call   : 2020-05-18T23:00:00.000+0000
spring-boot oracle12c timezone-offset
2个回答
0
投票

[请使用java.util.TimeZone.getDefault();检查Java服务器默认时间区域]另一个问题可能是从mysql / postgre休眠读取,它们取决于默认日历,而如果未传递prepare-statement()日历,则取决于默认日历。默认为UTC。

这里要考虑的几点:

  • 总是保存为UTC在数据库中:在某些情况下,您希望将服务器移到其他时区,而不希望记录生效。
  • 通过任何API调用
  • 请确保发送/接收数据之前将日期和数据/时间转换为字符串] >>。除非,否则必须进行时间转换(例如:每个国家/地区的促销时间是从12:00 AM到6:00 AM)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
    public static final String dateFormat = "dd-MMM-yyyy HH:mm";

    public static Date getDate(String date) {
        return getDate(date, dateFormat);
    }

    public static Date getDate(String date, String stringFormat) {
        if (date == null || date.length() == 0)
            return null;

        try {
            return new SimpleDateFormat(stringFormat).parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static String getDateFormatted(Date date) {
        return DateUtil.getDateFormatted(date, dateFormat);
    }

    public static String getDateFormatted(Date date, String stringFormat) {
        if (date == null)
            return "";

        return new SimpleDateFormat(stringFormat).format(date);
    }
}


public class UserBean {
    @JsonIgnore // Just to ignore sending to API
    private Date lastLogInDate;

    private String lastLogInDateFormatted;

    public Date getLastLogInDate() {
      return lastLogInDate;
    }

    // Auto create the String formatted verion of the date on setter
    public void setLastLogInDate(Date lastLogInDate) {
      this.lastLogInDate = lastLogInDate;
      this.lastLogInDateFormatted = DateUtil.getDateFormatted(lastLogInDate, "dd-MMM-yyyy HH:mm");
    }

    public String getLastLogInDateFormatted() {
      return lastLogInDateFormatted;
    }

    public void setLastLogInDateFormatted(String lastLogInDateFormatted) {
      this.lastLogInDateFormatted = lastLogInDateFormatted;
    }
}

// Receive params from API
public class OrderParam {
      public String orderDate;
    // ...
    // ...
}

// Convert String Date to java.util.Date
public class OrderService {
      public void processOrder(OrderParam param) {
        Date orderDate = DateUtil.getDate(param.orderDate);
        // .....
        // ..
    }
}

-1
投票

我认为,即使您的服务器和用户界面在同一时区上运行。有时代码本身可能正在从其他时区(例如数据库时区)获取时间。使用日历获取和存储时间。日历使用它们所在服务器的时区。确保将属性用作用于将日期存储为String

© www.soinside.com 2019 - 2024. All rights reserved.