簡體   English   中英

如何在兩個值之間獲取java中的年份列表?

[英]How to get list of year in java between two value?

我嘗試在 Java 中獲取年份列表。 例如,我只想打印從 2018 年到當年的年份。 任何人都可以幫助我嗎?

您可以使用LocalDateLocalDateTime ( jdk 8+ ):

LocalDate fromDate =  LocalDate.of(2018, 3, 11);
LocalDate toDate = LocalDate.now(); // 2020-03-11
long yearsD = fromDate.until(toDate, ChronoUnit.YEARS); // 2 years

LocalDateTime fromDateTime =  LocalDateTime.of(2018, 3, 11, 5, 45, 30);
LocalDateTime toDateTime = LocalDateTime.now(); // 2020-01-11T10:00:00.0000
long yearsDT = fromDateTime.until(toDateTime, ChronoUnit.YEARS); // 2 years

您可以執行以下操作:

List<Integer> years = new ArrayList<Integer>();
int endYear = Calendar.getInstance().get(Calendar.YEAR);
for(int year = 2018;year <= endYear; year++){
    System.out.println(year);// if you just want to print the years.
    years.add(year);// if you want to store the years in an array list.
}

在這里, Calendar.getInstance().get(Calendar.YEAR)可用於獲取當前年份。 正如您已經知道起始年份(例如 2018 年),我們可以使用它來創建一個循環以獲得所需的結果。

暫無
暫無

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

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