【问题标题】:Spring DateTime Conversion service exceptionSpring DateTime 转换服务异常
【发布时间】: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


    【解决方案1】:

    您遇到的具体异常让我有点吃惊,所以我想查看整个堆栈跟踪。

    话虽如此,您正在尝试使用格式字符串HH:mm 以格式dd/MM/yy HH:mm:ss 解析Strings。这会导致ParseException,因为它不知道如何处理String (dd/MM/yy) 的前导日期部分。

    尝试以下方法:

    <bean id="timeFormat" class="java.text.SimpleDateFormat">
        <constructor-arg value="dd/MM/yy HH:mm" />
    </bean>
    

    这将捕获您尝试表示的完整时间(尽管它会使用您可能不想要的系统时区)。

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 2014-06-09
      • 2011-03-12
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      相关资源
      最近更新 更多