【问题标题】:Java How to use for loop to populate Year and Month list?Java如何使用for循环填充年月列表?
【发布时间】:2019-06-27 02:50:30
【问题描述】:

如何循环显示年份和月份以显示在输出下方? 显示时间限制为当前月份和年份 此外,显示 3 年,包括截至日期的年份。意思是如果现在是 2019 年,请显示 2018 年和 2017 年。

我尝试使用一些代码作为 java 应用程序运行,希望得到下面的预期输出,但这是我尝试并得到的。

如果有人能在这里阐明一些问题,将不胜感激。

public class TestClass {
public static void main(String[] args) {
    Calendar today = Calendar.getInstance();
    //month=5, index starts from 0
    int month = today.get(Calendar.MONTH);
    //year=2019
    int year = today.get(Calendar.YEAR);

    for(int i = 0; i < 3; i++) {    //year
        for(int j= 0; j <= month; j++) {    //month
        System.out.println("Value of year: " + (year - 2)); //start from 2017 and iterate to 2 years ahead
        System.out.println("Value of month: " + (month + 1)); //start from January (index val: 1) and iterate to today's month
        }
    }
}

}

预期输出:

2017 1 2017 2 2017 3 2017 4 2017 5 2017 6 2017 7 2017 8 2017 9 2017 10 2017 11 2017 12

2018 1 2018 2 2018 3 2018 4 2018 5 2018 6 2018 7 2018 8 2018 9 2018 10 2018 11 2018 12

2019 1 2019 2 2019 3 2019 4 2019 5 2019 6

【问题讨论】:

标签: java for-loop calendar


【解决方案1】:

试试下面的代码。我正在使用 java 8 和 java.time.LocalDate,

LocalDate currentDate = LocalDate.now();
int year = currentDate.getYear();
int month = currentDate.getMonthValue();

for (int i = year - 2; i <= year; i++) {
    for (int j = 1; j <= 12; j++) {
        if (i == year && j == month) {
            System.out.print(i + " " + j + " ");
            break;
        }
            System.out.print(i + " " + j + " ");
        }
    }
}

输出

2017 1 2017 2 2017 3 2017 4 2017 5 2017 6 2017 7 2017 8 2017 9 2017 10 2017 11 2017 12 2018 1 2018 2 2018 3 2018 4 2018 5 2018 6 2018 7 2018 8 2018 9 2018 10 2018 11 2018 12 2019 1 2019 2 2019 3 2019 4 2019 5 2019 6 

【讨论】:

  • 试过了,但对我来说,它停在 2019 5 而不是 2019 6 。所以我在 j 中加了 1 ,它对我来说非常有用。 System.out.println(i + " " + (j + 1) + " " );
  • 你确定你已经正确实现了for循环吗?我很确定它会打印 2019 06。请仔细检查循环条件。
  • 所以我刚才还在我的代码中使用 java.util.calendar,同时还修改了我的循环条件,使其与您建议的相同。将其更改为使用 java.time.LocalDate,是的,它打印了 2019.06。现在意识到使用localtime时,索引值从1开始,而在java.util.calendar中,索引值从0开始
【解决方案2】:

tl;博士

YearMonth                        // Represent a specific month as a whole.
.now(                            // Determine the current month as seen in the wall-clock time used by the people of a particular region (a time zone).
    ZoneId.of( "Asia/Tokyo" )    // Specify your desired/expected time zone.
)                                // Returns a `YearMonth` object.
.withMonth( 1 )                  // Move back to January of this year. Returns another `YearMonth` object rather than changing (mutating) the original, per the immutable objects pattern.
.minusYears( 2 )                 // Jump back two years in the past. Returns yet another `YearMonth` object.

java.time

您正在使用可怕的旧日期时间类,这些类在几年前已被现代 java.time 类取代。

另外,您忽略了时区问题。时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因区域而异。例如,Paris France 中午夜后几分钟是新的一天,而 Montréal Québec 中仍然是“昨天”。

Continent/Region 的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用 2-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

YearMonth

您只关心年份和月份,没有任何日期。所以使用YearMonth 类。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
YearMonth yearMonthNow = YearMonth.now( z ) ;

YearMonth yearMonthJanuaryTwoYearAgo = yearMonthNow.withMonth( 1 ).minusYears( 2 ) ;

一次增加一个月,边走边收集。

ArrayList< YearMonth > yearMonths = new ArrayList<>();
YearMonth ym = yearMonthJanuaryTwoYearAgo ;
while( ! ym.isAfter( yearMonthNow ) ) 
{
    yearMonths.add( ym ) ;
    // Set up the next loop.
    ym = ym.plusMonths( 1 ) ;
}

转储到控制台。

System.out.println( yearMonths ) ;

看到这个code run live at IdeOne.com

[2017-01, 2017-02, 2017-03, 2017-04, 2017-05, 2017-06, 2017-07, 2017-08, 2017-09, 2017-10, 2017-11, 2017- 12、2018-01、2018-02、2018-03、2018-04、2018-05、2018-06、2018-07、2018-08、2018-09、2018-10、2018-11、2018-12、 2019-01、2019-02、2019-03、2019-04、2019-05、2019-06]

如果要排除当前月份,请使用:

while( ym.isBefore( yearMonthNow ) ) 

【讨论】:

  • 我在旧版本中维护它,因为该应用程序的一些用户仍在使用旧 Java。无论如何,这对我来说是很好的信息,我很高兴如何使用较新的 java 来完成它。非常感谢,伙计
  • @vlina 大多数 java.time 功能在ThreeTen-Backport 项目中向后移植到 Java 6 和 Java 7。旧的日期时间类真的很糟糕;避开他们。
【解决方案3】:

编辑:在循环中使用年份和月份

for(int i = year-2; i <= year; i++) {    //year

    for(int j= 1; (j <= 12 || (j == month && i == year)); j++) {    //month
        System.out.println("Value of year: " + i); //start from 2017 and iterate to 2 years ahead
        System.out.println("Value of month: " + j); //start from January (index val: 1) and iterate to today's month
    }
}

【讨论】:

  • 如何满足int month = today.get(Calendar.MONTH); 的需求?
  • @ScaryWombat:抱歉,我完全误读了这个问题。我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多