首先使用数据口DateTime
因为要精确到秒,所以使用DateTime
在java实体类中使用Timestamp
private Timestamp Time;
Timestamp与数据库当中的DateTime是对应的数据类型
创建工具类TimeTool
public class TimeTool implements Converter<String, Date> {
@Override
public Date convert(String s) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
类里的包
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
在spring-mvc.xml文件中配置一下信息
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 自定义参数绑定 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<property name="converters">
<list>
<!-- 日期类型转换 -->
<bean class="com.ssm.utils.CustomDateConverter"/>
</list>
</property>
</bean>
注意事项
千万注意,应为数据库当中使用的是DateTime,它的格式是“yyyy-MM-dd HH:mm:ss”,所以在jsp页面当中,一定要精确到秒,否则会报错
错误信息如下:
Field error in object 'product' on field 'departureTime': rejected value [2019-08-14 07:35]; codes
[typeMismatch.product.departureTime,typeMismatch.departureTime,typeMismatch.java.util.Date,ty
peMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
codes [product.departureTime,departureTime]; arguments []; default message [departureTime]];
default message [Failed to convert property value of type 'java.lang.String' to required type
'java.sql.Timestamp' for property 'departureTime'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert from type
[java.lang.String] to type [java.sql.Timestamp] for value '2019-08-14 07:35'; nested exception is
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]]