1

I need to convert date with pattern "yyyy-MM-dd" to String format "dd.MM.yyyy". Now i have this. Method getAsText() doesn't work meanwhile setAsText working. What i do wrong?

DateEditor.java

@Component
public class DateEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String value) {
        try {
            setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
        } catch (Exception ex) {
            setValue(null);
        }
    }

     @Override
    public String getAsText() {

        String sdf = "";

        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            dateFormat.setLenient(true);//-

            Date date = dateFormat.parse((String) getValue());
            sdf = new SimpleDateFormat("dd.MM.yyyy").format(date);

            System.out.println(sdf);
        } catch (ParseException p) {}

        return sdf;
    }

}

Initbinder

@InitBinder
    public void initBinder(WebDataBinder dataBinder) {
         dataBinder.registerCustomEditor(Date.class,new DateEditor());
}
Vytsalo
  • 670
  • 3
  • 9
  • 19
  • 2
    Define how is it "not working". I can think of several ways this might be broken, and I don't want to list them all. – M. Prokhorov Oct 03 '19 at 11:22
  • It's just printing the first date format, but not converting. p.printStackTrace(); show nothing – Vytsalo Oct 03 '19 at 11:25
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Oct 03 '19 at 11:36
  • It is probably not execute this method, but why? – Vytsalo Oct 03 '19 at 11:58
  • Would it be possible that you [create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) with clear statement of expected result, observed result and how they differ? I think it would greatly help answering the question. – Ole V.V. Oct 04 '19 at 15:33
  • Date in db -> 1966-10-12. Expectation result = 12.10.1966 – Vytsalo Oct 10 '19 at 08:49
  • Debug shows the correct "return" value but, in form i have the old one – Vytsalo Oct 10 '19 at 08:50

0 Answers0