测试类
@Data
public class FormatTime {
private LocalDateTime startTime;
private Date endTime;
}
控制器
@RestController
public class TestController {
@GetMapping("/test")
public Object test() {
FormatTime formatTime = new FormatTime();
formatTime.setStartTime(LocalDateTime.now());
formatTime.setEndTime(new Date());
return formatTime;
}
}
1. 未经过格式化
访问localhost:8080/test
将会返回以下结果
{
"endTime": 1587089043726,
"startTime": "2020-04-17T10:04:03.726"
}
2.使用 @JsonFormat 注解
使用@JsonFormat
注解格式化时间,应该算是一个基本操作了,大部分开发者都应用此种方式,简单方便。
@Data
public class FormatTime {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime startTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date endTime;
}
返回结果
{
"startTime": "2020-04-17 10:21:31",
"endTime": "2020-04-17 10:21:31"
}
3. 全局配置 (1)
配置全局日期格式化处理类
@Configuration
public class LocalDateTimeSerializerConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
@Bean
public LocalDateTimeSerializer localDateTimeDeserializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
}
}
返回结果
{
"startTime": "2020-04-17 10:23:29",
"endTime": "2020-04-17T02:23:29.136+0000"
}
这种方式可支持Date
类型和LocalDateTime
类型并存,那么有一个问题就是现在全局时间格式是yyyy-MM-dd HH:mm:ss
,但有的字段却需要yyyy-MM-dd
格式咋整?
那就需要配合@JsonFormat
注解使用,在特定的字段属性添加@JsonFormat
注解即可
3. 全局配置 (2)
在application.properties
中配置
#返回日期格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#接受参数日期格式化
spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
返回结果
{
"startTime": "2020-04-17T10:36:33.922",
"endTime": "2020-04-17 10:36:33"
}