簡體   English   中英

在 Spring 引導中使用 LocalDateTime RequestParam

[英]Use LocalDateTime RequestParam in Spring boot

當我嘗試使用帶有 LocalDateTime 的 RequestParam 時遇到問題:

public ResponseData getTotalRevenue(@RequestParam(value = "startDate")
                                    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
                                    @RequestParam(value = "endDate")
                                    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate){
                        //....
            }

我用這個參數測試:

/total-revenue?startDate=2022-07-28&endDate=2022-08-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.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] 
for value '2022-07-28'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-07-28]]

任何人都可以幫助我嗎? 太感謝了。

DateTimeFormat.ISO.DATE_TIME 是一種需要日期和時間的格式,但您的請求只包括日期。 請改用 DateTimeFormat.ISO.DATE。

該錯誤是不言自明的:

值的解析嘗試失敗 [2022-07-28]]

我認為您希望startDateendDate的類型為LocalDate而不是LocalDateTime因為您想表示日期。

無論如何,您傳遞的查詢參數是錯誤的DateTimeFormat 而不是DateTimeFormat.ISO.DATE_TIME ,您應該使用DateTimeFormat.ISO.DATE

public ResponseData getTotalRevenue(@RequestParam(value = "startDate")
                                    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDateTime startDate,
                                    @RequestParam(value = "endDate")
                                    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDateTime endDate) {
    //....
}

是一個示例供您參考。

查看所有 ISO 格式的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM