Home > Back-end >  How to format HTML Input Type Date to an actual Date Object
How to format HTML Input Type Date to an actual Date Object

Time:08-01

I want to use a Form with a Date in Thymeleaf that adds my Projekt Object the Attribute datum_start and datum_end. The Problem is that these to Object are from the Date class. I wonder if there is a posibillity to input a Date Object in HTML or something in the direction.

<form action="#" th:action="@{neuesProjektErstellen}" th:object="${Projekt}" method="post">
    Name: <input type="text" th:field="*{name}" required/><br>
    Beschreibung: <input type="text" th:field="*{beschreibung}" required/><br>
    Startdatum: <input type="date" th:field="*{datum_start}" id="datum_startProjektAdd" required/><br>
    Enddatum: <input type="date" th:field="*{datum_end}" id="datum_endProjektAdd" equired/><br>
    <br>
    <input type="submit" value="Projekt erstellen"/>
    <input type="reset" value="Clear"/>

That is my Form

@PostMapping("/neuesProjektErstellen")
public String neuesProjektErstellen(@ModelAttribute(value = "Projekt") Projekt Projekt, Model m)
{
    if(Projekt.getDatum_start()==null || Projekt.getDatum_end()==null)
      {
        return "DatumFalsch";
    }
    else {
        projektRepository.save(Projekt);
        return "redirect:Projekte";
    }
}

This is the Post Route Handler

@Column (columnDefinition = "date")
private Date datum_start;
@Column (columnDefinition = "date")
private Date datum_end;

And this are the two Attributes from the Class Projekt

CodePudding user response:

For date handling you should add a @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) to your date fields. See this article for some examples on how to handle date objects in spring https://www.baeldung.com/spring-date-parameters

P.S. Generally LocalDate is preferable to Date for most bigger applications I believe

  • Related