美文网首页
springboot的spring.jackson.date-f

springboot的spring.jackson.date-f

作者: 瓦大西精神小伙丶澎 | 来源:发表于2020-12-30 19:40 被阅读0次
image.png

看起来数据库的格式非常完美,但是数据库字段look_date 是 datetime类型,java里没有datetime类型,这样一来如果你不在后端做处理,那么模型属性Date来接收一定会出问题.我通过实验证明最后拿到的是一个时间戳.

第一 解决时间格式问题

1.可以通过application.propertis配置文件中配置

#日期格式 
spring.jackson.date-format= yyyy-MM-dd hh-mm-ss
spring.jackson.time-zone= GMT+8

但是我使用的时候是无效的.

2.可以在模型属性上加注解

 @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd")
  private Date date;

3.也可以通过自己写一个配置类

@Configuration
public class CoreConfiguration extends WebMvcConfigurationSupport {
   /**
     * 时间日期格式化
     */
    @Bean
    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(simpleDateFormat);
        converter.setObjectMapper(mapper);
        return converter;
    }
    //添加转换器
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //将我们定义的时间格式转换器添加到转换器列表中,
        //这样jackson格式化时候但凡遇到Date类型就会转换成我们定义的格式
        converters.add(jackson2HttpMessageConverter());
    }
}

image.png

通过接口看来模型属性Date类型成功匹配数据库库datetime类型

第二 解决日期时间不准确的问题

如果获取或者存储的时间早了那么请查看链接数据库的url

jdbc:mysql://localhost:3306/house?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
解决办法:
最后的UTC会把你的时间提前8小时改成, serverTimezone=Asia/Shanghai 即可

如果晚了8小时网上有很多办法

相关文章

网友评论

      本文标题:springboot的spring.jackson.date-f

      本文链接:https://www.haomeiwen.com/subject/ybzhoktx.html