Reputation: 137
How do I pass a start date and end date in the @RequestParam
which are of type java.time.Instant
?
Currently, I have a created a sample endpoint with this logic below:
@GetMapping("sample")
public void sample(@RequestParam("from") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Instant startDate,
@RequestParam("to") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Instant endDate) {
// custom logic ...
}
But this doesn't work when I pass the start date and end date in the yyyy-MM-dd
format.
For example:
http://localhost:port/sample?from=2019-10-10&to=2019-10-15
I'm getting the below error:
Failed to convert value of type 'java.lang.String' to required type 'java.time.Instant'.
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.
Upvotes: 10
Views: 10883
Reputation: 16949
Replace DateTimeFormat.ISO.DATE
by DateTimeFormat.ISO.DATE_TIME
.
The default time format that Instant expects : yyyy-MM-dd'T'HH:mm:ss.SSSXXX
The code below :
@GetMapping("sample")
public void sample(@RequestParam("from") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant startDate,
@RequestParam("to") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant endDate) {
System.out.println("Start date :" + startDate);
System.out.println("Start date :" + endDate);
}
Tested with this data:
http://localhost:8081/sample?from=2010-01-01T12:00:00.000Z&to=2010-01-02T12:00:00.000Z
Output:
Start date: 2010-01-01T12:00:00Z
End date: 2010-01-02T12:00:00Z
This should work.
Upvotes: 7
Reputation: 79620
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.
Upvotes: 1
Reputation: 1343
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"
Upvotes: 0
Reputation: 5978
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)
Upvotes: 0