parse localDateTime string correctly into spring b

2020-04-20 23:29发布

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 ??

2条回答
We Are One
2楼-- · 2020-04-21 00:20

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)
{

}
查看更多
老娘就宠你
3楼-- · 2020-04-21 00:21

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.

查看更多
登录 后发表回答