简体   繁体   中英

How do I indicate to Spring Boot to use UTC time zone for date parameters?

I have the following 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;

When I make a request with "endDate": "2018-10-11" , it prints

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

This is messing up SQL queries because I'm testing if hit_date <= #{endDate} . It should be returning results from 2018-10-11 but it's not, because Spring Boot has interpreted the date as 2018-10-10. How can I get Spring Boot to use UTC time zone when parsing the date parameters to an API?

Spring Boot 1.5.13, MyBatis 3.4.5, MyBatis Spring 1.3.1

Use local date , the problem is that when dates are involved, java tries to convert the date to the server timezone, since the is no time zone specified, it takes the hour ad UTC and then converts, LocalDate does not contain the timezone info, so, the date will be parsed as is.

Sorry, forgot to mention, to handle local date time you need to use jackson-datatype-jsr310 . Then, as the example says, you can annotate your class with:

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

There is some way to define jackson feature in springmvc when you use springboot.

  1. Use properties. spring.jackson.xxxx . Such as you want to set timezone. use add spring.jackson.time-zone=xxx in your application.properties

  2. define a spring bean which implement Jackson2ObjectMapperBuilderCustomizer

  3. you can directly create ObjectMapper bean in spring ,custom you want.

I changed the class to java.time.LocalDate and added this dependency

    <!-- 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM