How to pass an Instant start, end date as @RequestParam

Viewed 3364

How can I pass an Instant startDate, endDate as a @RequestParam Instant startDate, Instant endDate with pattern yyyy-MM-dd so the request will looks like localhost:port/api/entity=startDate=2019-10-10?endDate=2019-10-15 any ideas how to perform it?

@RequestParam("from") @DateTimeFormat(iso = ISO.DATE) Instant startDate,
            @RequestParam("to") @DateTimeFormat(iso = ISO.DATE) Instant endDate)

it does not help I'm getting Failed to convert value of type 'java.lang.String' to required type 'java.time.Instant' even tried with pattern. Also the problem is that when I've entity created at yyyy-MM-dd HH:mm:ss how can I ignore the seconds so when I pass date and hours only it will display the result.

4 Answers

Replace DateTimeFormat.ISO.DATE by DateTimeFormat.ISO.DATE_TIME.

The format that Instant takes : yyyy-MM-dd'T'HH:mm:ss.SSSXXX

The code below :

@GetMapping("/getlist")
public void method(@RequestParam("from") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant startDate,
            @RequestParam("to") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant endDate)) {

      // code

}

This should work.

Your date strings conform to ISO 8601 format for a date. Therefore, you should use LocalDate as the type i.e.

RequestParam("from") @DateTimeFormat(iso = ISO.DATE) LocalDate startDate,
            @RequestParam("to") @DateTimeFormat(iso = ISO.DATE) LocalDate endDate)

Here is an overview of the java.time types.

If you want to have a proper DateTime format to provide the capability of handling timezone for you, I suggest you use the following pattern:

@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX") Date myDate 

It's a common ISO DATE_TIME Format and you can easily convert it to Instant afterward.

e.g. "2000-10-31T01:30:00.000-05:00"

You can use yyyy-MM-dd HH:mm:ss the date format that your want.

@RequestParam("from") @DateTimeFormat(iso = "yyyy-MM-dd HH:mm:ss")
                                      Instant startDate, 
@RequestParam("to") @DateTimeFormat(iso = "yyyy-MM-dd HH:mm:ss") 
                                    Instant endDate)
Related