parse localDateTime string correctly into spring boot @pathVariable

扶醉桌前 提交于 2020-01-05 04:22:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!