簡體   English   中英

Java Android 錯誤:當前月份不能在結束月份之后

[英]Java Android error : current Month cannot be after end Month

我正在嘗試為材料日期范圍選擇器對話框設置約束。 這個想法是將可選日期的范圍從當天限制到一個月后的同一天。

我有一種建立約束的方法:

public CalendarConstraints.Builder setCalendarConstraints() {
    CalendarConstraints.Builder constraints = new CalendarConstraints.Builder();

    long min = setMinDate();
    long max = setMaxDate();

    constraints.setStart(min);
    constraints.setEnd(max);

    return constraints;
}

並使用以下兩種方法來獲取最小和最大日期:

// Maximum date for the date picker is the current date + 1 month
public long setMaxDate() {
    LocalDate now = LocalDate.now();
    LocalDate max;

    if (now.getMonthValue() == 12) {
        max = LocalDate.of(now.getYear(), 1, now.getDayOfMonth());
        max.plusYears(1);
    } else {
        max = LocalDate.of(now.getYear(), now.getMonth().plus(1), now.getDayOfMonth());
    }
    return max.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli();
}

兩周前我測試我的應用程序時一切正常,所以我認為問題出在我們現在在 12 月。 當我們在 12 月時,我嘗試在當前年份中添加一年,當它看起來不起作用時,因為我有以下錯誤:

java.lang.IllegalArgumentException:當前月份不能在結束月份之后

java.time類使用不可變對象

LocalDate::plusYears()方法不適用於LocalDate本身。 正如 Javadoc 所說,它返回一個新的 object,即原始LocalDate Object 的副本,但添加了一年。

所以你需要寫:

 max = max.plusYears(1);

順便說一句,你不需要檢查 12 月。

LocalDate max = LocalDate.now().plusMonths(1)

無論您是否在十二月,都可以解決問題。

嘗試

LocalDate.now().plusMonths( 1 );

最大

暫無
暫無

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

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