Spring MVC中自定义日期类型格式转换器

在Spring MVC中,自定义日期类型格式转换器可以通过实现Converter接口或使用@DateTimeFormat注解。以下是两种方法的详细说明:


方法一:全局自定义转换器(推荐)

1. 创建日期转换器类

实现 org.springframework.core.convert.converter.Converter 接口:

java 复制代码
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateConverter implements Converter<String, Date> {

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public Date convert(String source) {
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
        try {
            return format.parse(source);
        } catch (ParseException e) {
            throw new IllegalArgumentException("日期格式错误,请使用 " + DATE_FORMAT, e);
        }
    }
}
2. 注册转换器到Spring容器
方法1:通过配置类实现 WebMvcConfigurer
java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDateConverter());
    }
}
方法2:通过配置applicationContex.xml实现:
xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 1. 声明自定义转换器 -->
    <bean id="stringToDateConverter" class="com.example.converter.StringToDateConverter"/>

    <!-- 2. 配置 ConversionService -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <ref bean="stringToDateConverter"/>
                <!-- 可添加其他转换器,如日期转字符串 -->
            </set>
        </property>
    </bean>

    <!-- 3. 启用 MVC 注解驱动并关联 ConversionService -->
    <mvc:annotation-driven conversion-service="conversionService"/>

    <!-- 其他配置(如组件扫描、视图解析器等) -->
    <context:component-scan base-package="com.example.controller"/>
</beans>

方法二:局部使用 @DateTimeFormat

直接在实体类字段上标注日期格式:

java 复制代码
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;

public class MyEntity {

    @DateTimeFormat(pattern = "yyyy/MM/dd")
    private Date createTime;

    // Getter & Setter
}

使用 Java 8 的 DateTimeFormatter(更安全)

如果使用Java 8+,建议用 DateTimeFormatter 替代 SimpleDateFormat

java 复制代码
import org.springframework.core.convert.converter.Converter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {

    private static final DateTimeFormatter FORMATTER = 
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public LocalDateTime convert(String source) {
        return LocalDateTime.parse(source, FORMATTER);
    }
}

注册方式与全局转换器相同。


注意事项:

  1. 时区处理:如果涉及跨时区,需在格式化时指定时区:

    java 复制代码
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        .withZone(ZoneId.systemDefault());
  2. 异常处理 :转换失败时会抛出 IllegalArgumentException,可在Controller中捕获并处理。

  3. 多格式支持:若需支持多种格式,可在转换器中按顺序尝试不同格式。


通过以上步骤,即可实现全局或局部的日期格式自定义转换。

相关推荐
还是鼠鼠27 分钟前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven
Xiaokai丶1 小时前
Java 8 新特性深度剖析:核心要点与代码实战
java
灵魂猎手1 小时前
3. MyBatis Executor:SQL 执行的核心引擎
java·后端·源码
Galaxy在掘金1 小时前
从业8年,谈谈我认知的后端架构之路-1
java·架构
努力努力再努力wz2 小时前
【c++深入系列】:万字详解模版(下)
java·c++·redis
还是大剑师兰特2 小时前
Spring面试题及详细答案 125道(1-15) -- 核心概念与基础1
spring·大剑师·spring面试题·spring教程
瓦特what?3 小时前
关于C++的#include的超超超详细讲解
java·开发语言·数据结构·c++·算法·信息可视化·数据挖掘
是乐谷3 小时前
阿里云杭州 AI 产品法务岗位信息分享(2025 年 8 月)
java·人工智能·阿里云·面试·职场和发展·机器人·云计算
Java水解4 小时前
Java中的四种引用类型详解:强引用、软引用、弱引用和虚引用
java·后端
lifallen4 小时前
JCTools 无锁并发队列基础:ConcurrentCircularArrayQueue
java·开发语言·数据结构·算法