Map HTML input date to LocalDate of Java Object

ersu picture ersu · Sep 25, 2017 · Viewed 8.7k times · Source

I have a input field (type: 'date') - who could I map it to a 'LocalDate' field in my Object using Thymeleaf?

Object

public class Project {

    @Id
    private int id;

    private LocalDate startDate;

    private LocalDate endDate;
}

HTML input

How could I map the input field correctly to the LocalDate startDate or endDate?

Controller

//GetMapping for Projects is also there, but I didn't paste it to keep clarity

@PostMapping("/add/save")
public String saveProject(@Valid @ModelAttribute("project") Project project,
                          BindingResult bindingResult,
                          Model model,
                          RedirectAttributes redirectAttributes) {

// bindingResult has error, because Thymeleaf can't map from the input-field to startDate

  if (!bindingResult.hasErrors()) {
      project.save(project);
      return "redirect:/admin/projects/list";
  } else {
      return "admin/projects/add";
  }
}

Exception

Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'startDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.time.LocalDate] for value '2017-09-08'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2017-09-08]

Answer

Tom Melo picture Tom Melo · Sep 25, 2017

You have a few options:

1 - Try:

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate startDate;

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate endDate;

2 - Use Thymeleaf Extras