java判断某年某月有几天,可以这样弄:// 将日历里的日设为0,日历就会倒转到上一个月的最后一天
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; }
Java获得某月第一天和最后一天(Calendar实现)
摘自:https://blog.csdn.net/u011287511/article/details/54344402