LocalDateTime格式化配置-springboot

本文介绍了在JDK8中使用java.time包处理时间日期,并展示了在Spring Boot项目中如何通过配置类全局格式化Date和LocalDateTime,包括实体类、Web层的处理,并给出了配置前后的测试结果对比。

LocalDateTime格式化配置-springboot


在项目中日期格式化是最常见的问题,之前涉及的 java.util.Date 和 java.util.Calendar 类易用性差,不支持时区,非线程安全,对日期的计算方式繁琐,而且容易出错,因为月份是从0开始的,从 Calendar 中获取的月份需要加一才能表示当前月份。

在 JDK8 中,一个新的重要特性就是引入了全新的时间和日期API,它被收录在 java.time 包中,借助新的时间和日期API可以以更简洁的方法处理时间和日期。

配置

定义一个配置类,在里面定义两个 Bean 即可完成全局日期格式化处理,同时还兼顾了 Date 和 LocalDateTime 并存

package com.pocket.ishop.common.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @ClassName: LocalDateTimeConfig
 * @Description: 配置LocalDateTime格式化
 * @Author: liwei
 * @Date: 2019-12-04
 * @Version 1.0
 */
@Configuration
public class LocalDateTimeConfig {

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

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

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern)));
        };
    }

    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter(){
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String s) {
                if (StringUtils.isEmpty(s)){
                    return null ;
                } else {
                    return LocalDateTime.parse(s, DateTimeFormatter.ofPattern(pattern));
                }
            }
        };
    }

}

实体类

package com.example.demo.entity;

import com.example.demo.common.base.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.time.LocalDateTime;

/**
 * <p>
 *
 * </p>
 *
 * @author liwei
 * @since 2020-04-07
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@ApiModel(value = "User对象", description = "")
public class User extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "用户名")
    private String username;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value =  "盐值")
    private String salt;

    @ApiModelProperty(value = "创建时间")
    protected LocalDateTime createTime;


}

Web层

  @GetMapping("/test")
    public User test() {
        User user = userService.getById("3");
        user.setCreateTime(LocalDateTime.now());
        return  user;
    }

测试结果

没加LocalDateTime配置之前
没加LocalDateTime配置之前
加上LocalDateTime配置
加上LocalDateTime配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值