Search code examples
javaspring-bootthymeleaflocaldate

Map HTML input date to LocalDate of Java Object


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

  <form action="#"
      th:action="@{|/admin/projects/add/save|}"
      th:object="${newProjects}"
      method="POST"
      class="form-horizontal">
        
    <input type="date" class="form-control" id="startDate"
                       placeholder="Project start"
                       th:field="*{startDate}"/>

    <input type="date" class="form-control" id="endDate"
                       placeholder="Project start"
                       th:field="*{endDate}"/>
                       
</form>

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]


Solution

  • 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