-1

I am very new to SpringBoot. I have some issues converting String value which I get from jsp form to LocalTime. For example I have jsp form where I write my input:

<div class="col-lg-7">
    <form:input path="shiftStart" type="time" name="shiftStart" id="shift-start-time" min="08:00:00" max="17:45:00" step="900"></form:input>
</div>

and I have the following controller where I try to convert this String value to LocalTime variable:

@PostMapping("/add-shift")
public String createShiftForm(@ModelAttribute("shiftForm") @Valid TimeTable timeTable, BindingResult result, Model model, @RequestParam("shiftStart") String shiftStart ){
    if (result.hasErrors()) {
        return "/add-shift";
    }
   LocalTime startShift = LocalTime.parse(shiftStart);
   model.addAttribute("shiftStart",startShift);
   return "redirect:/admin";
}

and I am getting the following error:

Failed to convert property value of type java.lang.String to required type java.time.LocalTime for property shiftEnd; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.time.LocalTime] for value 09:15; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [09:15]

Can anybody please help?

Catalin Pirvu
  • 175
  • 2
  • 8
joel4
  • 33
  • 7

3 Answers3

1

I found a solution: just need to pass parametr without @RequestParametr in Controller and convert string to localtime in local variable like this:

 @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) LocalTime  shiftStart

Here it was discussed:How to use LocalDateTime RequestParam in Spring? I get "Failed to convert String to LocalDateTime"

joel4
  • 33
  • 7
0

You need to parse the String value to LocalTime to do so you need to figure out in which format you're receiving it and you just add this code :

LocalTime startShift = LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm"));
Elarbi Mohamed Aymen
  • 1,617
  • 2
  • 14
  • 26
0

As Elarbi said, I also recommand using a standard formatter:

DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; 

LocalTime lt = LocalTime.parse("10:15:45", formatter);

Or directly:

LocalTime lt = LocalTime.parse("10:15:45", DateTimeFormatter.ISO_LOCAL_TIME);

For a list of patterns consider this from official Oracle doc.

Catalin Pirvu
  • 175
  • 2
  • 8
  • that didn`t help unfortunately – joel4 Apr 12 '20 at 20:00
  • glad you've found a solution; I don't like the solution you've found as if someone edits your form and sends a different format, you'll deal with an exception, you don't catch it and the users gets no information about it – Catalin Pirvu Apr 13 '20 at 16:50