Springboot中LocalDateTime对象返回给前端,格式化
1.需求
后端日期时间对象,是LocalDateTime类型,直接返回前端,是数组形式
希望以正常的日期时间字符串格式返回
2.思路
1.@JsonFormat注解
2.消息转化器
3.解决方案
3.1 使用注解(不推荐)
在实体类的LocalDateTime属性上面,添加注解
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime updateTime;
缺点: 每个日期时间属性都要添加,麻烦
(图片来源网络,侵删)
3.2 扩展SpringMVC框架的消息转化器,实现返回日期时间的格式化(推荐)
3.2.1 配置类: config.WebMvcConfiguration
该config已实现了登录拦截器,和knife4j生成接口文档、静态资源映射(已从代码中删除),
现添加时间按格式转换功能extendMessageConverters
/** * 配置类,注册web层相关组件 */ @Configuration @Slf4j public class WebMvcConfiguration extends WebMvcConfigurationSupport { //扩展SpringMVC框架的消息转化器,例如实现返回日期时间的格式化 @Override protected void extendMessageConverters(List
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...