Home > OS >  Failed to convert String to LocalDate
Failed to convert String to LocalDate

Time:09-15

I have a method what should find object from database by inserted date. I used LocalDate class, but if I try it in swagger I get a error message. I need only dates and format should be dd/MM/yyyy. Please help :)

Error message in swagger: Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '15/04/2022'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [15/04/2022]

Entity:

@Entity
@Table(name = "\"order\"")
public class Order {

    @Column(name = "delivery_date", nullable = false)
    private LocalDate deliveryDate

Dto:

@Data
public class OrderInfo implements Serializable {
    private LocalDate deliveryDate;

Method:

@GetMapping("/orders/date")
    @Operation(summary = "Find all orders by date")
    public List<OrderInfo> findAllOrderByDate(LocalDate date){
        return orderService.findAllOrdersByDate(date);
    }

CodePudding user response:

Perhaps this will help. Convert String date to LocalDate:

String dateString = "07/11/1957";  // dd/MM/yyyy

java.time.format.DateTimeFormatter formatter = 
                java.time.format.DateTimeFormatter.ofPattern("dd/MM/yyyy");

java.time.LocalDate date = java.time.LocalDate.parse(dateString, formatter);

System.out.println(date); // Display LocalDate in console Window

CodePudding user response:

Assuming that you're using a request param to accept the data parameter

@GetMapping("/orders/date")
@Operation(summary = "Find all orders by date")
public List<OrderInfo> findAllOrderByDate(
    @RequestParam("date") @JsonFormat("dd/MM/yyyy") LocalDate date
){
    return orderService.findAllOrdersByDate(date);
}

Please ensure that you have valid Jackson dependencies

  • Related