SpringBoot时间类型转换

在前后端交互中,前端通常传递日期为String,后端需要转换为Date存入数据库。本文介绍在SpringBoot中如何自定义DateConverter并进行注册,避免手动转换的繁琐步骤,包括实现WebMvcConfigurer接口和添加拦截器来完成类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发中前端常常传的日期类型是String的,而后端在存入数据库中的时候,是Date类型的,这时候我们通常都是手动转一下,或者在Converter中转一下,这样是比较麻烦的。 下面介绍一下boot开发spring类型转换
1.自定义DateConverter

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间类型转换类
 */
public class DateConverter implements Converter<String, Date> {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date convert(String s) {
        if(StringUtils.isEmpty(s)) {
            return null;
        }
        try {
            return simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;

    }
}

2.注册引用类型转换类
2.1 自定义一个类 实现WebMvcConfigurer接口并 使用@Configuration注解
2.2 实现WebMvcConfigurer接口中的addInterceptors方法
2.3 注册引用时间类型转换类

import com.example.springboot_day04_01.utils.DateConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
		//实现WebMvcConfigurer接口中的addInterceptors方法
    public void addFormatters(FormatterRegistry registry) {
    	//注册引用时间类型转换类
        registry.addConverter(new DateConverter());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值