Monday, October 3, 2011

Spring Custom Date Editor

Recently I had a need to convert a date specified in this sample format "10/01/2010 01:05:20" into java.util.Date, with the date specified in a spring configuration file:

<bean name="aBean" p:id="1" class="org.bk.BeanClass" p:fromDate="01/10/2011 01:05:00" p:toDate="01/10/2011 02:05:00" p:counterId="1"/>

The hour and second part of the date was however being dropped by Spring.

The fix is simple, register a custom date editor, which understands the appropriate date format:

 <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
     <map>
       <entry key="java.util.Date">
          <bean class="org.springframework.beans.propertyeditors.CustomDateEditor">
           <constructor-arg>
        <bean class="java.text.SimpleDateFormat">
                     <constructor-arg><value>MM/dd/yyyy hh:mm:ss</value></constructor-arg>
                  </bean>           
           </constructor-arg>
           <constructor-arg index="1"><value>true</value></constructor-arg>
          </bean>
       </entry>
     </map>
    </property>
 </bean>






No comments:

Post a Comment