Spring转换服务-三种日期格式转换
本文仅提供本文作者阅读,严禁转载
步骤
- 在springmvc配置转换服务
- 编写对应的日期转换工具类
(代码/图片)如下
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 以上两段配置可以省略 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 扫描controller包 -->
<context:component-scan base-package="com.gec.ssm.controller"></context:component-scan>
<!-- 视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--转换服务-->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<!--日期转换工具类的包路径-->
<bean class="com.gec.ssm.util.DateConverter" />
</list>
</property>
</bean>
</beans>
日期转换工具类
package com.gec.ssm.util;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author 三七
* @date 2022/7/16
*/
public class DateConverter implements Converter<String, Date> {
SimpleDateFormat[] simpleDateFormats = new SimpleDateFormat[]{
new SimpleDateFormat("yyyy年MM月dd日"),
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyy/MM/dd")
};
@Override
public Date convert(String time) {
for (SimpleDateFormat simpleDateFormat : simpleDateFormats) {
try {
return simpleDateFormat.parse(time);
} catch (ParseException e) {
return null;
}
}
return null;
}
}