Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 580
aklaffenboeck Avatar asked Mar 04 '26 19:03

aklaffenboeck


2 Answers

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

like image 137
Tom Melo Avatar answered Mar 06 '26 08:03

Tom Melo


Adding @DateTimeFormat(pattern = "yyyy-MM-dd") annotation to LocalDate variable solves the problem.

like image 44
Orumiya Avatar answered Mar 06 '26 09:03

Orumiya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!