3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊
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
您正在使用多年前被現(xiàn)代java.time類取代的可怕的舊日期時(shí)間類。
另外,您忽略了時(shí)區(qū)問題。時(shí)區(qū)對(duì)于確定日期至關(guān)重要。對(duì)于任何給定時(shí)刻,日期在全球范圍內(nèi)因地區(qū)而異。例如,在法國(guó)巴黎午夜過后幾分鐘是新的一天,而在魁北克蒙特利爾仍然是“昨天” 。
以、或 等格式指定適當(dāng)?shù)臅r(shí)區(qū)名稱。切勿使用 2-4 字母縮寫,例如或因?yàn)樗鼈?em>不是真正的時(shí)區(qū)、未標(biāo)準(zhǔn)化,甚至不是唯一的(?。?code>Continent/RegionAmerica/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.of( "America/Montreal" ) ; LocalDate today = LocalDate.now( z ) ;
YearMonth
你只關(guān)心年份和月份,沒有任何日期。所以使用YearMonth
類。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
YearMonth yearMonthNow = YearMonth.now( z ) ;
YearMonth yearMonthJanuaryTwoYearAgo = yearMonthNow.withMonth( 1 ).minusYears( 2 ) ;
一次增加一個(gè)月,邊走邊收集。
ArrayList< YearMonth > yearMonths = new ArrayList<>();
YearMonth ym = yearMonthJanuaryTwoYearAgo ;
while( ! ym.isAfter( yearMonthNow ) )
{
yearMonths.add( ym ) ;
// Set up the next loop.
ym = ym.plusMonths( 1 ) ;
}
轉(zhuǎn)儲(chǔ)到控制臺(tái)。
System.out.println( yearMonths ) ;
在 IdeOne.com 上查看此代碼的實(shí)時(shí)運(yùn)行。
[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]
如果要排除當(dāng)前月份,請(qǐng)使用:
while( ym.isBefore( yearMonthNow ) )

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
試試下面的代碼。我正在使用 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

TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
在循環(huán)中使用年份和月份
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
}
}
添加回答
舉報(bào)