用calendar.add(Calendar.Month,1)的方法,獲取下一月相同的日期java
若是第一個月有31天,第二個月不足31天,加上一月後是自動調整到第二個月的最後一天,仍是順延到下一個月?spa
用的環境是JAVA SE-1.8。code
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try{ Date d = sdf.parse("2017-01-31"); Calendar cld = Calendar.getInstance(); cld.setTime(d); cld.add(Calendar.MONTH, 1); Date d2 = cld.getTime(); System.out.println(sdf.format(d)+"加一月:"+sdf.format(d2)); //閏年的狀況 d = sdf.parse("2016-01-31"); cld = Calendar.getInstance(); cld.setTime(d); cld.add(Calendar.MONTH, 1); d2 = cld.getTime(); System.out.println(sdf.format(d)+"加一月:"+sdf.format(d2)); }catch(Exception e){ e.printStackTrace(); }
輸出結果:orm
2017-01-31加一月:2017-02-28
2016-01-31加一月:2016-02-29get
答案是自動調整爲下月的最後一天。it
那麼按月累加的狀況就要注意了,假如要取得某個月的31號,必須從有31號的月份得到,而不是每一個循環添加1月。io
get,add,set方法ast
package cn.itcast_02; import java.util.Calendar; /* * public void add(int field,int amount):根據給定的日曆字段和對應的時間,來對當前的日曆進行操做。(根據日曆字段,增長或減去) * public final void set(int year,int month,int date):設置當前日曆的年月日。(直接設置日曆值); */ public class CalendarDemo { public static void main(String[] args) { // 獲取當前的日曆時間 Calendar c = Calendar.getInstance(); // 獲取月 int year = c.get(Calendar.YEAR); // 獲取月 int month = c.get(Calendar.MONTH); // 獲取日 int date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // // 三年前的今天 // c.add(Calendar.YEAR, -3); // // 獲取月 // year = c.get(Calendar.YEAR); // // 獲取月 // month = c.get(Calendar.MONTH); // // 獲取日 // date = c.get(Calendar.DATE); // System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // 5年後的10天前 c.add(Calendar.YEAR, 5); c.add(Calendar.DATE, -10); // 獲取月 year = c.get(Calendar.YEAR); // 獲取月 month = c.get(Calendar.MONTH); // 獲取日 date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日");// 2021年11月30日 System.out.println("-----------"); c.set(2011, 11, 11); // 獲取月 year = c.get(Calendar.YEAR); // 獲取月 month = c.get(Calendar.MONTH); // 獲取日 date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); } }