Java日期转换注解配置date format时间失效

 更新时间:2022年12月12日 16:45  点击:477 作者:刨红薯的小羊竿尔

引言

今天生产上突然出现了列表日期错误,与数据库实际差了8个小时;

这下可尴尬了,之前迭代都是正常,肯定是那里出幺蛾子了,一顿排除,原来是新添加拦截器继承WebMvcConfigurationSupport导致date-format时间格式失效了。

顺带学习了一下@JsonFormat和@DateTimeFormat的用法:

注解@JsonFormat主要是后台到前台的时间格式的转换

注解@DateTimeFormat主要是前后到后台的时间格式的转换

一、@DateTimeFormat

主要解决前端时间控件传值到后台接收准确的Date类属性的问题,我们可以在需要接收的类中对应的时间类型属性上加上@DateTimeFormat注解,并在注解中加上pattern属性。

// 出生年月日 
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss") 
private Date birthday;

二、@JsonFormat

该注解主要解决后台从数据库中取出时间类型赋予java对象的Date属性值无法在前端以一定的日期格式来呈现,默认返回的是一个带时区的格式串,不符合我们日常要呈现的yyyy-MM-dd格式的日期。 同样,我们在对应的接收对象时间类型上加上@JsonFormat注解,并在注解中加上pattern属性以及timezone属性,例如:

// 出生年月日
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;

pattern:是你需要转换的时间日期的格式

timezone:是时间设置为东八区,避免时间在转换中有误差;GMT+8表示我们以东八区时区为准。

三、application.yml文件配置

1、数据库配置时区serverTimezone=Asia/Shanghai或者serverTimezone=GMT%2B8

解决mysql从数据库查询的时间与实际时间相差8小时:

spring.datasource.url=jdbc:mysql://10.35.105.25:3306/database?characterEncoding=utf-8&serverTimezone=GMT%2B8

2、配置spring.jackson

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

spring:
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss

四、SpringBoot拦截器

SpringBoot拦截器SpringBoot拦截器继承WebMvcConfigurationSupport导致date-format时间格式失效

1、解决办法不继承WebMvcConfigurationSupport,修改为实现WebMvcConfigurer接口

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Resource
    private JwtInterceptor jwtInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                //拦截所有url
                .addPathPatterns("/**")
                //排除登录url
                .excludePathPatterns("/", "/login");
    }
}

2、另外还有方式就是引入fastjson替换jackson

3、也可以继承WebMvcConfigurationSupport重写configureMessageConverters,自定义转换器处理日期类型转换

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
            .dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
            .serializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
    converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
    converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}

以上就是Java日期转换注解配置date format时间失效的详细内容,更多关于Java日期转换注解配置的资料请关注猪先飞其它相关文章!

原文出处:https://juejin.cn/post/7174041322343366692

[!--infotagslink--]

相关文章