java判斷某年某月有幾天,能夠這樣弄:// 將日曆裏的日設爲0,日曆就會倒轉到上一個月的最後一天java
1 public static int getDaysOfYearMonth(int year, int month){ 2 3 Calendar cal = Calendar.getInstance(); 4 5 cal.set(Calendar.YEAR, year); 6 7 cal.set(Calendar.MONTH, month - 1); 8 cal.set(Calendar.DAY_OF_MONTH, 1);
9 cal.add(Calendar.MONTH, 1); 10 // 將日曆裏的日設爲0,日曆就會倒轉到上一個月的最後一天 11 12 cal.set(Calendar.DAY_OF_MONTH, 0); 13
return cal.get(Calendar.DAY_OF_MONTH); 14 }
/** * 獲取某年某月最後一天 * 此函數有缺陷: windows單元測試沒有問題\linux單獨運行此函數沒有問題\linux聯調會跳出這樣的結果:2019年2月最後一天是31天 * * @param year 年 * @param monthFrom1 1-12月 * @author * @return */ public static int getDaysOfMonth1(int year, int monthFrom1) { logger.info("Year=" + year + ", monthFrom1=" + monthFrom1); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, monthFrom1 - 1); //獲取某月最大天數 int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); { for (int m = 1; m <= 13; m++) { cal.set(Calendar.MONTH, m - 1); int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); logger.info("Year=" + year + ", m=" + m + ", days=" + days); } } logger.info("Year=" + year + ", monthFrom1=" + monthFrom1 + ", lastDay=" + lastDay); return lastDay; }
摘自:https://blog.csdn.net/u011287511/article/details/54344402 linux