如何指示Spring Boot使用UTC时区作为日期参数?

时间:2018-10-11 21:03:43

标签: java spring spring-boot

我有以下API

public ResponseEntity<ResponseDataToSeller> getTrackingDataByDate(@RequestBody RequestBodyBySeller requestBodyBySeller) {
    System.out.println(requestBodyBySeller.getEndDate());
    System.out.println(requestBodyBySeller.getEndDate().getDate());
    System.out.println(requestBodyBySeller.getEndDate().getHours());

public class RequestBodyBySeller {
    @ApiModelProperty(dataType="Date", notes = "endDate",required = true)
    Date endDate;

当我向"endDate": "2018-10-11"发出请求时,它会打印

2018-10-11 16:54:45.897  INFO 11996 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 3 ms
Wed Oct 10 20:00:00 EDT 2018
10
20

这搞砸了SQL查询,因为我正在测试是否hit_date <= #{endDate}。它应该从2018-10-11返回结果,但不是,因为Spring Boot将日期解释为2018-10-10。将日期参数解析为API时,如何让Spring Boot使用UTC时区?

Spring Boot 1.5.13,MyBatis 3.4.5,MyBatis Spring 1.3.1

3 个答案:

答案 0 :(得分:0)

使用local date,问题是当涉及日期时,java尝试将日期转换为服务器时区,因为未指定时区,因此需要花费一小时的广告UTC,然后进行转换,LocalDate会不包含时区信息,因此日期将按原样进行解析。

抱歉,忘记了,要处理本地日期时间,您需要使用jackson-datatype-jsr310。然后,如示例所示,您可以使用以下代码注释课程:

@JsonFormat(pattern = "dd/MM/yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate birthdate;*

答案 1 :(得分:0)

使用springboot时,有一些方法可以在springmvc中定义杰克逊功能。

  1. 使用属性。 spring.jackson.xxxx。 如您要设置时区。在您的spring.jackson.time-zone=xxx

  2. 中使用添加application.properties
  3. 定义一个实现Jackson2ObjectMapperBuilderCustomizer

  4. 的spring bean
  5. 您可以在春季根据自己的需要直接创建ObjectMapper bean。

答案 2 :(得分:0)

我将类更改为java.time.LocalDate并添加了此依赖项

    <!-- For LocalDate to be deserialized using ISO format -->
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>

https://stackoverflow.com/a/46884603/148844