在JDK1.8中引入新的日期类型API-LocalDateTime。但是在使用的时候发现返回得时间格式为"yyyy-MM-dd T HH:mm:ss"。很明显返回格式与正常使用格式有明显不同。
要想得到正常格式"yyyy-MM-dd HH:mm:ss"。SpringBoot中有两种方式供选择。
方法一:使用全局配置解决(推荐)
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * LocalDataTime 类型全局配置 */ @Configuration public class LocalDateTimeSerializerConfig { @org.springframework.beans.factory.annotation.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()); } }
这种方式相对来说更方便。
方法二:在实体上加入注解(搜索的时候说这个可以,在我的项目中这样用不生效,不知道原因)
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("company")
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 企业名称
*/
private String name;
/**
* 企业全称
*/
private String fullName;
/**
* 企业头像
*/
private String picture;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
private LocalDateTime createTime;
}
@JsonFormat:本质上与全局配置原理是相同的,全局配置一次付出,终身受用,这个需要在每个LocalDateTime类型得字段上使用。
未经处理直接返回得LocalDateTime:
{ "code": 0, "message": "操作成功", "data": { "id": 3, "name": "dwie@lc.com", "fullName": "sfewovadl", "picture": "/home/upload/uploadImg/82bb045ca63d49e28de4e9ed858d7339067a976e9cbb2a4ca4e4c773d753a71.jpg", "createTime": "2021-04-25T07:36:09" } }
可以看到 createTime:2021-04-25T07:36:09
使用全局配置:
{ "code": 0, "message": "操作成功", "data": { "id": 3, "name": "dwie@lc.com", "fullName": "sfewovadl", "picture": "/home/upload/uploadImg/82bb045ca63d49e28de4e9ed858d7339067a976e9cbb2a4ca4e4c773d753a71.jpg", "createTime": "2021-04-26 05:43:55" } }
问题结局。至于添加@JsonFormat注解的方法在我的项目中不生效,也不知道具体原因。有知道的小伙伴麻烦留言告知。谢谢!!!!