【问题标题】:parse localDateTime string correctly into spring boot @pathVariable将 localDateTime 字符串正确解析为 spring boot @pathVariable
【发布时间】:2020-04-08 05:21:26
【问题描述】:

我正在尝试获取带有时间戳的用户的用户的所有数据:

@GetMapping("/datum/{userID}/{timeStamp}")
    List<Datum> getDataSingleUserTimeRange(@PathVariable Long userID, @PathVariable LocalDateTime timeStamp)
    {
          ....
    }

现在为了测试这个 Spring Boot rest api,我在 postman 中调用了 GET 和 url - http://localhost:8080/datum/2/2019-12-15T19:37:15.330995

但它给了我错误提示:无法将类型“java.lang.String”的值转换为所需类型“java.time.LocalDateTime”

我该如何解决这个问题??

【问题讨论】:

  • : 是 URI 中的一个特殊字符。我会在这里使用时间戳而不是格式化的日期时间
  • 您的变量名为time。但是路径变量被命名为timeStamp
  • @JBNizet 正确,但更正后,我收到此错误 - '无法将'java.lang.String'类型的值转换为所需类型'java.time.LocalDateTime'
  • @JBNizet 请参阅this question

标签: spring spring-boot spring-data-jpa spring-data


【解决方案1】:

您需要 @DateTimeFormat 具有与您的输入匹配的自定义模式

@GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(@PathVariable Long userID, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS") LocalDateTime timeStamp)
{

}

【讨论】:

  • 给出can't convert String to LocalDateTime, type mismatch error...
  • 我在 spring boot 2.x 上对其进行了测试,这对我有用@MaifeeUlAsad
  • 我会在我打开桌面并将实际日志发送给您时再次这样做..
  • 请看this snap,这就是我使用这种方法时得到的结果
  • 因为您传递的输入日期只有 2 位毫秒,所以请按照 yyyy-MM-dd'T'HH:mm:ss.SS@MaifeeUlAsad 之类的格式使用格式化程序
【解决方案2】:

我不知道这是否是最谦虚的方式,但这是我所做的:

@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);
    }

作为字符串传递并对其进行解析。还有dateTime.truncatedTo(ChronoUnit.NECESARRY_UNIT);也可以用。

【讨论】:

  • 我试过了,但这让我无法将字符串转换为 localDateTime..
猜你喜欢
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 2020-07-11
  • 2018-03-14
  • 2019-01-11
  • 2016-04-27
相关资源
最近更新 更多