所以我觀察了如何@FutureOrPresent抱怨當前日期。進一步除錯我的代碼
public class MyCustomDeserializer extends JsonDeserializer<Instant> {
private DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy").withZone(ZoneOffset.UTC);
@Override
public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
LocalDate date = LocalDate.parse(p.getText(), fmt);
Instant instant = date.atStartOfDay(ZoneId.of("UTC")).toInstant();
return instant;
}
}
除錯給了我這個狀態:

知道如何解決這個問題嗎?如果有幫助的話,我在亞洲/加爾卡特地區
如果我fromDate在 JSON 檔案中傳遞當前日期,則會收到此錯誤:
fromDate Must Be Of Future Or Present
POJO 有這種格式
@JsonDeserialize(using = MyCustomDeserializer.class)
@JsonSerialize(using = MyCustomSerializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
@NotNull(message = "Please provide From Date")
@FutureOrPresent(message = "From Date Must Be Of Future Or Present")
private Instant fromDate;
uj5u.com熱心網友回復:
您可能會收到此回應,因為您將一天的開始作為一天中的時間,并且您在 UTC 中執行此操作。
比較也使用一天的開始,但不包括相等性,或者在您通過 UTC 的一天開始時使用 UTC 中的當前時間,根據您的描述,這永遠不會是未來時間,它最多可以被認為是相等的.
嘗試以下示例并檢查結果是否被視為過去或通過驗證:
public static Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
// parse the JSON String (that's the date part)
return LocalDate.parse(p.getText(), fmt)
// use your system's time of day
.atTime(LocalTime.now())
// shift the time zone afterwards
.atZone(ZoneId.of("UTC"))
// and return it as an Instant
.toInstant();
}
這種方法只有在您獲得今天的日期時才有意義(對我而言,目前),將執行日期用于將來的日期似乎不合適。
uj5u.com熱心網友回復:
問題是您正在使用一天開始的時間
如果您使用今天的日期,那將永遠是過去的日期。如果您使用今天并想要一個將來的瞬間,您可以在一天結束時獲得一個瞬間
LocalDateTime localDateTime= date.atTime(23, 59, 59);
localDateTime.atZone( ZoneId.of("UTC"));
localDateTime.toInstant();
這會給你一個最有可能在今天但也永遠在未來或現在最有可能的瞬間
您還可以使用未來一分鐘而不是一天結束時的瞬間。
當前時間的瞬間可能會失敗,因為請求到達目的地需要時間,并且有一點緩沖是很好的
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/338584.html
