Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set date format for an input text using Spring MVC

How can I set the format for a Date in a text field with Spring MVC?

I'm using the Spring Form tag library and the input tag.

What I get now is something like this Mon May 28 11:09:28 CEST 2012.

I'd like to show the date in dd/MM/yyyy format.

like image 562
davioooh Avatar asked May 28 '12 13:05

davioooh


2 Answers

register a date editor in yr controller :

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(LocalDate.class, new LocalDateEditor());
}

and then the data editor itself can look like this :

public class LocalDateEditor extends PropertyEditorSupport{

 @Override
 public void setAsText(String text) throws IllegalArgumentException{
   setValue(Joda.getLocalDateFromddMMMyyyy(text));
 }

 @Override
 public String getAsText() throws IllegalArgumentException {
   return Joda.getStringFromLocalDate((LocalDate) getValue());
 }
}

I am using my own abstract utility class (Joda) for parsing dates, in fact LocalDates from Joda Datetime library - recommended as the standard java date/calendar is an abomination, imho. But you should get the idea. Also, you can register a global editor, so you don't have to do it each controller (I can't remember how).

like image 189
NimChimpsky Avatar answered Sep 27 '22 22:09

NimChimpsky


Done! I just added this method to my controller class:

@InitBinder
protected void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
            dateFormat, false));
}
like image 38
davioooh Avatar answered Sep 28 '22 00:09

davioooh