【发布时间】:2015-10-18 17:03:04
【问题描述】:
我遇到了这个异常:
将 java.lang.String 类型的属性值转换为所需类型 java.util.Date for property startTime; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value 10:00; nested exception is java.lang.IllegalArgumentException 失败
当尝试输入时间并通过表单发送到控制器时。
我在日期方面遇到了同样的问题,但设法使用我在网上找到的一个例子来解决它:
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="dd/MM/yyyy" />
</bean>
<bean id="appointment" class="com.nw.model.Appointment">
<property name="theDate">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="22/05/1983" />
</bean>
</property>
<property name="startTime">
<bean factory-bean="timeFormat" factory-method="parse">
<constructor-arg value="22/05/1983 10:00:34" />
</bean>
</property>
<property name="endTime">
<bean factory-bean="timeFormat" factory-method="parse">
<constructor-arg value="22/05/1983 10:00:23" />
</bean>
</property>
</bean>
'theDate' 没有抛出任何错误,似乎没问题。当表单无法发布时,它确实会错误地返回给我,但这完全是另一个问题 - 也许这个修复可以解决这个问题。
日期 - 当从日期选择器中选择时会解析得很好,当表单无法发布并返回时的结果是 Sun Oct 18 00:00:00 BST 2015 - 如果我尝试使用这个日期发送,那么它也会在这里抛出异常。
我在配置中添加了一小段时间,所以现在完整的格式化程序部分是:
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="dd/MM/yyyy" />
</bean>
<bean id="timeFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="HH:mm" />
</bean>
<bean id="appointment" class="com.nw.model.Appointment">
<property name="theDate">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="22/05/1983" />
</bean>
</property>
<property name="startTime">
<bean factory-bean="timeFormat" factory-method="parse">
<constructor-arg value="22/05/1983 10:00:34" />
</bean>
</property>
<property name="endTime">
<bean factory-bean="timeFormat" factory-method="parse">
<constructor-arg value="22/05/1983 10:00:23" />
</bean>
</property>
</bean>
表单使用的是thymeleaf,模型的字段是Date对象。
如果需要,我可以发布模型/表格的其余部分。提前致谢。
【问题讨论】:
标签: java spring date spring-mvc datetime