Set date format for an input text using Spring MVC

后端 未结 3 1414
既然无缘
既然无缘 2020-12-15 13:33

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

3条回答
  •  無奈伤痛
    2020-12-15 13:51

    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).

提交回复
热议问题