Reputation: 188
So to start off, this code is working when I use @DateTimeFormat(pattern = "HH:mm")
. But as soon as I change it to @DateTimeFormat(pattern = "hh:mm")
it stops working. I'm pretty new to spring so I'm not sure where the problem could be coming from. All I want to do is save a time to my DB.
The Error:
Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalTime] for value '12:00';
This is the object that I am mapping to the form:
@Entity
@Table(name = "Schedule")
@NoArgsConstructor
@Getter
@Setter
public class Schedule {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@DateTimeFormat(pattern = "hh:mm")
private LocalTime startTime;
@DateTimeFormat(pattern = "hh:mm")
private LocalTime endTime;
@Column(name = "days")
private String days;
public Schedule(LocalTime startTime, LocalTime endTime, String days) {
this.startTime = startTime;
this.endTime = endTime;
this.days = days;
}
}
And this is my controller:
@Controller
@RequestMapping("/schedules")
@AllArgsConstructor
public class WebScheduleController {
ScheduleService scheduleService;
@GetMapping
public String getSchedules(Model model) {
List<Schedule> schedules = scheduleService.getSchedules();
model.addAttribute("scheduleList", schedules);
model.addAttribute("schedule", new Schedule());
return "schedules";
}
@PostMapping
public String createSchedule(@ModelAttribute("schedule") Schedule schedule,Model model ){
scheduleService.createSchedule(schedule);
return "redirect:/schedules/";
}
}
And this is the HTML form:
<form method="post" th:action="@{/schedules}" th:object="${schedule}" class="col card p-3 mb-5">
<div class="form-group">
<label for="startTime">Start time</label>
<input id="startTime" placeholder="Enter start time" required type="time" th:field="*{startTime}"/>
</div>
<div class="form-group">
<label for="endTime">End time</label>
<input id="endTime" placeholder="Enter end time" required type="time" th:field="*{endTime}" />
</div>
<div class="form-group">
<label for="days">Days</label>
<input id="days" placeholder="Enter days" required type="text" th:field="*{days}" />
</div>
<input type="submit" class="btn btn-primary" value="Create Schedule">
</form>
Upvotes: 1
Views: 318
Reputation:
have you try to remove am/pm? maybe this String am/pm also trying to be part of time when sending data. which you database dont allow String in Date.
Upvotes: 1