SpringMvc日期转换器(注解+自定义)

本文介绍了在SpringMVC框架中解决日期格式问题的方法,包括使用@DateTimeFormat注解及自定义日期转换器两种方式,并提供了详细的代码示例。

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

为啥要写日期转换器?

SpringMvc不知道日期的格式,不写日期转换器将会出现日期格式未知,从而报400错误,这也是常见的参数异常错误。
方法一:

1、如果查询类让我们自己写,那么在属性前面加上@DateTimeFormat(pattern = “yyyy-MM-dd”) ,即可将String转换为Date类型,如下

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

方法二:

自定义日期转换器实现

1、创建自定义日期转换类,需要实现Converter抽象类

2、自定义日期转换

package com.xue.utils;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.springframework.core.convert.converter.Converter;
 
/**
 * 定义时间转换器springmvc
 * Converter<S, T>
 * S:source要转换的源类型 
 * T:target 要转换成的数据类型
 * @author 
 *
 */
public class MyConvert implements Converter<String, Date> {
	@Override
	public Date convert(String source) {
		Date result = null;
		try {
			//指定日期的格式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			//将源数据转为指定日期格式
			result = sdf.parse(source);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//返回转换后的时间格式日期
		return result;
	}
 
}

3、告诉springmvc自己定义的日期格式

在springmvc核心配置文件中声明自定义类

<!-- 配置注解驱动,使用自定义日期转换器 -->
	<mvc:annotation-driven conversion-service="myConvert"/>
	
	<!-- 日期转换器 -->
		<!-- 定义转换器 -->
	<bean id="myConvert" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<!-- 自己的写的转换器全路径名 -->
				<bean class="com.xue.utils.MyConvert"></bean>
			</set>
		</property>
	</bean>
 

注意:日期格式出错是一件比较复杂的事情,关键是你不知道是日期参数出错,所以当springmvc遇到400错误,首先考虑参数错误,如果有时间入库操作,此时得考虑日期格式出错,日期转换器就用上了。

扩展:

date类型转换为json字符串时,返回的是long time值,如果需要返回指定的日期的类型的get方法上写上@JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”) ,即可将json返回的对象为指定的类型。

@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")  
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")  
public Date getCreateTime() {  
return this.createTime;  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值