问题
I'm trying to get all data of a user of a user with a timestamp:
@GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(@PathVariable Long userID, @PathVariable LocalDateTime timeStamp)
{
....
}
Now to test this Spring Boot rest api, in postman, I made this call GET
and url - http://localhost:8080/datum/2/2019-12-15T19:37:15.330995
.
But it gives me error saying : Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'
How can I resolve this ??
回答1:
You need @DateTimeFormat with custom pattern that matches to your input
@GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(@PathVariable Long userID, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS") LocalDateTime timeStamp)
{
}
回答2:
I don't know if it is the most modest way to do this or not, but here is what I have done :
@GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(@PathVariable Long userID, @PathVariable String timeStamp)
{
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse(timeStamp, formatter);
...
return datumRepository.findUsingTime(start,end);
}
Passed as string and parsed that. AnddateTime.truncatedTo(ChronoUnit.NECESARRY_UNIT);
can be used as well.
来源:https://stackoverflow.com/questions/59344476/parse-localdatetime-string-correctly-into-spring-boot-pathvariable