SpringBoot返回date日期格式化
时间: 2023-07-01 15:11:43 浏览: 71
在Spring Boot应用程序中,您可以使用注解`@JsonFormat`来指定日期字段的格式化方式。您可以在类的属性上使用它,也可以在getter方法上使用它。
以下是一个示例:
```java
import com.fasterxml.jackson.annotation.JsonFormat;
public class User {
private String name;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date birthdate;
// getters and setters
}
```
在上面的示例中,`@JsonFormat`注解指定了`birthdate`属性的格式为`yyyy-MM-dd`。
您还需要确保您的应用程序配置了`Jackson`日期格式化程序。您可以在`application.properties`文件中添加以下配置:
```
spring.jackson.date-format=yyyy-MM-dd
```
或者,您可以在`WebMvcConfigurer`中配置`ObjectMapper`:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureJackson(Jackson2ObjectMapperBuilder builder) {
builder.simpleDateFormat("yyyy-MM-dd");
}
}
```
这将使`Jackson`使用`yyyy-MM-dd`格式对所有日期进行序列化和反序列化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)