2014-01-22 53 views
6

我正在開發使用Spring 3.1和Joda-Time的多語言應用程序。如何使Spring Joda-Time格式化程序使用非標準語言環境?

讓我們想象一下我有一個這樣的命令對象:

private class MyCommand { 
    private LocalDate date; 
} 

當我要求英國或美國語言環境,它可以正確地分析並結合date不使用相應的日期格式,例如任何問題21/10/2013和10/21/13。 但是,如果我有一些區域設置像格魯吉亞new Locale("ka")它不綁定有效日期21.10.2014。所以我需要掛鉤到Spring格式化器,以便能夠提供我自己的格式,每個區域。我有一個可以從語​​言環境解析日期格式的bean。你能指點我正確的方向,我怎麼能做到這一點?

回答

2

你必須實現自己的org.springframework.format.Formatter

public class DateFormatter implements Formatter<Date> { 

    public String print(Date property, Locale locale) { 
     //your code here for display 
     DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, LocaleContextHolder.getLocale()); 
     String out = df.format(date); 
     return out; 
    } 

    public Date parse(String source, Locale locale) 
     // your code here to parse the String 
    } 
} 

在Spring配置:

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" > 
    <property name="formatterRegistrars"> 
     <set> 

     </set> 
    </property> 
    <property name="converters"> 
     <set> 

     </set> 
    </property> 
    <property name="formatters"> 
     <set> 
      <bean class="com.example.DateFormatter" /> 
     </set> 
    </property> 
</bean> 

<mvc:annotation-driven conversion-service="conversionService"/> 

希望它可以幫助你!

相關問題