Springboot 全局时间格式化(LocalDateTime,Date)

、yml配置(项目中使用时间格式为Date) 推荐

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

二、注解形式(针对某一个时间格式化) 推荐

@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")

三、全局配置 (针对LocalDateTime,Date等做全局配置) 

    方式一:推荐

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;


@JsonComponent
public class DateFormatConfig {

    @Value("${spring.jackson.date-format}")
    private String dateFormat;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {
        return builder -> {
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat(dateFormat);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    .dateFormat(df);
        };
    }

    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateFormat));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){
        return builder -> builder.serializerByType(LocalDateTime.class,             
        localDateTimeDeserializer());
    }

//    @Bean
//    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
//
//        return builder ->  {
//            //返回时间数据序列化
//            builder.serializerByType(LocalDateTime.class, LocalDateTimeSerializer());
//            //接收时间数据反序列化
//           builder.deserializerByType(LocalDateTime.class, LocalDateTimeDeserializer());
//        };
//    }

}

方式二 (字段手动配置@JsonFormat 注解将不再生效)

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Configuration
public class DateFormatConfig2 {

    @Value("${spring.jackson.date-format}")
    private String dateFormat;

    public static DateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Bean
    @Primary
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new             
        LocalDateTimeDeserializer());
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

   
    @Component
    public class DateSerializer extends JsonSerializer<Date> {
        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException {
            String formattedDate = simpleDateFormat.format(date);
            gen.writeString(formattedDate);
        }
    }

    @Component
    public class DateDeserializer extends JsonDeserializer<Date> {

        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            try {
                return simpleDateFormat.parse(jsonParser.getValueAsString());
            } catch (ParseException e) {
                throw new RuntimeException("Could not parse date", e);
            }
        }
    }


    public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(DateTimeFormatter.ofPattern(dateFormat)));
        }
    }


    public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {
            return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(dateFormat));
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个快速构建Spring应用程序的开发框架。在Spring Boot中,可以轻松地使用注解和配置来进行日期格式全局日期格式可以确保应用程序中的所有日期在显示和解析时都遵循相同的格式。 要实现全局日期格式,首先需要创建一个自定义的日期格式器。可以通过创建一个继承自 WebMvcConfigurationSupport 的类,并覆盖其方法来实现自定义日期格式器。在该类中,可以调用 setDateFormatter 方法来设置日期格式器,将日期格式模式作为参数传递给自定义日期格式器。 例如,假设想在应用程序中将日期格式为"yyyy-MM-dd"格式。可以创建一个 CustomDateFormatter 类,实现 DateFormatter 接口,并在实现类的 toFormatter 方法中设置日期格式模式为"yyyy-MM-dd"。然后,在自定义的 WebMvcConfigurationSupport 类中,覆盖其 configureMessageConverters 方法,并在该方法中调用 setDateFormatter 方法来设置日期格式器为 CustomDateFormatter。 在应用程序中任何地方,只需要使用 @DateTimeFormat 注解,并指定日期格式即可将日期解析为指定格式。同样地,使用该注解在返回对象上,可以将日期字段格式为指定格式。 总而言之,Spring Boot 提供了全局日期格式的机制,使得应用程序中的日期在显示和解析时都能遵循统一的格式。通过自定义日期格式器,可以轻松地实现指定的日期格式,并在应用程序中使用 @DateTimeFormat 注解来格式和解析日期。这样,可以确保应用程序中的日期始终遵循相同的格式要求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值