This is the fifth day of my participation in the August Wen Challenge.More challenges in August

Recently I saw some posts introducing these two annotations, some of them are not accurate enough, so I will record them here

To use the @jsonFormat annotation, you need to add jackson-related dependencies to your project

<! -- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.123.</version>
</dependency>
Copy the code

To use the @datetimeformat annotation, you need to add springframework dependencies to your project

<! -- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.39.</version>
</dependency>
Copy the code
Note: SpringBoot’s spring-boot-start-Web contains dependencies related to Jackson, and spring-boot-starter-freemarker contains dependencies related to Spring Framework. There is no need to add additional dependencies. The development tool I’m using here is IDEA. You can see the POM dependency tree using Maven Helper
  • Maven Helper plug-in

  • Use Maven Helper to view the dependency tree

jackson

springframework

You can go to this website to find the dependency you want: mvnrepository.com

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	private LocalDateTime userCreateDate;
Copy the code

Format the date and time returned by the back end to the front end. Pattern is the converted format, and timezone is the timezone of the date and time

The default time zone in China is THE CST time zone. The difference between the CST time zone and CST time zone is 8 hours

@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime userCreateDate;
Copy the code

Format the date and time from the front end to the back end. Pattern is the converted format

conclusion

For POST requests, we typically use @RequestBody to receive JSON objects. If the object has date-time data in it, we can use the @jsonFormat annotation to format both the outgoing and incoming parameters

GET request parameters are concatenated after the URL, so @dateTimeFormat should be used to format the input parameter. Putting @requestBody in an object is invalid