【问题标题】:How to get data between two dates REST Spring如何在两个日期之间获取数据 REST Spring
【发布时间】:2020-01-23 11:34:24
【问题描述】:

我的控制器映射

@GetMapping("/fetch/{one_date}/{two_date}")
public List<CourierInfo> getData_between(@PathVariable(value = "one_date") @DateTimeFormat(pattern = "yyyyMMdd") LocalDateTime fromDate, @PathVariable(value = "two_date") @DateTimeFormat(pattern = "yyyyMMdd") LocalDateTime toDate) {
    return bookRepository.getData_between(fromDate, toDate);
}

我的自定义查询

@Query(nativeQuery = true, value="select c.cons_no, c.pick_date, from CourierInfo c where c.pick_date between :startDate and :endDate")

List getData_between(@Param("startDate") LocalDateTime date, @Param("endDate") LocalDateTime date2);

我路过

http://localhost:8080/book_api/fetch/2020-01-20/2020-01-20

我在这里尝试获取两个日期之间的数据。 我收到此错误

Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.PathVariable @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '"2020-01-20"'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value ["2020-01-20"]

【问题讨论】:

标签: java rest spring-boot


【解决方案1】:

检查这个主题: https://stackoverflow.com/a/53188501/4135813

问题与端点配置中缺少转换器有关

【讨论】:

  • 只需在控制器方法中的参数toDate前指定@DateTimeFormat(pattern="yyyyMMdd")
【解决方案2】:

首先停止使用java.util.Date并开始使用java-8日期时间API中的LocalDate,您可以使用DateTimeFormatter将输入的日期字符串解析为LocalDate

@GetMapping("/fetch/{one_date}/{two_date}")
public List<CourierInfo> getData_between(@PathVariable(value = "one_date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, @PathVariable(value = "two_date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate toDate) {
    return bookRepository.getData_between(fromDate, toDate);
}

在存储库中

@Query(nativeQuery = true, value="select c.cons_no, c.pick_date, from CourierInfo c where c.pick_date between :startDate and :endDate")
List<CourierInfo> getData_between(@Param("startDate") LocalDate date, @Param("endDate") LocalDate date2);

【讨论】:

  • 无法将“java.lang.String”类型的值转换为所需的“java.time.LocalDateTime”类型;这是我遇到的错误
  • 你能用请求和堆栈跟踪更新你的帖子吗@MayankS.Gupta
  • 请注意模式yyyyMMdd 接受20200120,而不是2020-01-20。为了标准,我会使用@DateTimeFormat(iso=ISO.DATE)
  • 由于您只有日期,请使用LocalDate,并确保输入请求日期格式应与DateTimeFormatter@MayankS.Gupta 匹配,尝试更新后的代码
猜你喜欢
  • 1970-01-01
  • 2019-04-19
  • 2020-03-02
  • 1970-01-01
  • 2019-05-07
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
相关资源
最近更新 更多