Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Spring Joda-Time formatter work with nonstandard locales?

I am developing a multilingual application using Spring 3.1 and Joda-Time.

Let's imagine I have a command object like this:

private class MyCommand {
    private LocalDate date;
}

When I request with UK or US locales it can parse correctly and bind date without any problems using corresponding dates format e.g. 21/10/2013 and 10/21/13 respectively. But if I have some locales like georgian new Locale("ka") it doesn't bind valid date 21.10.2014. So I need to hook into Spring formatters to be able to provide my own formats per locale. I have a bean which can resolve date format from the locale. Can you please point me into right direction how can I accomplish this?

like image 379
klor Avatar asked Jan 22 '14 01:01

klor


People also ask

Is Joda-Time deprecated?

Cause joda-time is deprecated.

Why use joda-Time?

Joda-Time provides support for multiple calendar systems and the full range of time-zones. The Chronology and DateTimeZone classes provide this support. Joda-Time defaults to using the ISO calendar system, which is the de facto civil calendar used by the world.

What is org Joda-Time?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.


1 Answers

You have to implement your own org.springframework.format.Formatter

Example

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
    }
}

In your spring config :

<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"/>

Hope it helps you!

like image 133
Mannekenpix Avatar answered Nov 05 '22 11:11

Mannekenpix