To format an input and output LocalDate
with SpringBoot, you can use the @DateTimeFormat
annotation provided by Spring Framework.
Here is an example of how to use @DateTimeFormat
to format a LocalDate
field in a SpringBoot application:
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
@RestController
public class MyController {
@GetMapping("/my-endpoint")
public String myEndpoint(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
// use the date parameter here
return "Received date: " + date.toString();
}
}
In the above example, the @DateTimeFormat
annotation is used to specify the pattern for the input date, which is expected to be in the format “yyyy-MM-dd”. The LocalDate
parameter will be automatically parsed from the input using the specified pattern.
Similarly, you can use @DateTimeFormat
to format a LocalDate
field in a response object as well. Here’s an example:
import org.springframework.format.annotation.DateTimeFormat;
public class MyResponse {
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate date;
// getter and setter
}
In this example, the @DateTimeFormat
annotation is used to specify the pattern for the output date, which will be formatted as a string in the specified format when returned as part of the MyResponse
object.