Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default value to LocalDateTime in @RequestParam [duplicate]

I have controller that is accepting the request with LocalDateTime as query parameter

@GetMapping("test")
public void test(@RequestParam(value = "date", required = false, defaultValue = ?) LocalDateTime date) {
    System.out.println("The date is : "+date);

}

I know we can set the default value for String and Integer using defaultValue in @RequestParam, but how to set the default value for LocalDateTime ?

like image 903
app Avatar asked Oct 23 '19 17:10

app


People also ask

What is the default value of LocalDateTime?

LocalDateTime is an immutable date-time object that represents a date-time with default format as yyyy-MM-dd-HH-mm-ss.

How do I initialize LocalDateTime?

The easiest way to create an instance of the LocalDateTime class is by using the factory method of(), which accepts year, month, day, hour, minute, and second to create an instance of this class. A shortcut to create an instance of this class is by using atDate() and atTime() method of LocalDate and LocalTime class.

How do I set default value in RequestParam?

By default, @RequestParam requires query parameters to be present in the URI. However, you can make it optional by setting @RequestParam 's required attribute to false . In the above example, the since query param is optional: @RequestParam(value="since", required=false) ).

Is LocalDateTime immutable?

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision.


1 Answers

You can use the spring expression language to set the default value for any object

@GetMapping("test")
public void test(@RequestParam(value = "date", required = false, defaultValue = "#{T(java.time.LocalDateTime).now()}") LocalDateTime date) {
    System.out.println("The date is : " + date);

}
like image 59
Deadpool Avatar answered Sep 25 '22 09:09

Deadpool