[Java] – Spring and dateformatter

We will perform it in our application configuration class(AppWeb Configuration), so that we don’t need to keep repeating this date setting on all the attributes of other system classes.

We will create a new method called mvcDataFormatterConverterService that returns a  FormattingConversionService type object. We need to do two things in this method:

  • We need to create a DefaultFormattingConversionService type object that will be responsible for format conversion service;
  • Create an object of type DateFormatterRegistrar that will make the date format of the record used for the conversion.

In this example, we want formatter the date in day/moth/year (dd/MM/yyyy).

@Bean
public FormattingConversionService mvcDataFormatterConverterService(){
    DefaultFormattingConversionService conversionService = 
                               new DefaultFormattingConversionService();
    DateFormatterRegistrar formatterRegistrar = 
                               new DateFormatterRegistrar(); 
    formatterRegistrar.setFormatter(new DateFormatter("dd/MM/yyyy")); 
    formatterRegistrar.registerFormatters(conversionService); 
    return conversionService; 
}

Now, we will implement the entity like:

@Entity
public class MyClass {
    [...]
    @DateTimeFormat
    private Calendar myDate;
    [...]
}

Look our form (jsp file):

My Date name="myDate" type="text" /> path="myDate" />

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s