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; }
-
import java.text.SimpleDateFormat;
-
import java.util.Calendar;
-
/**
-
* 获得该月第一天
-
* @param year
-
* @param month
-
* @return
-
*/
-
publicstatic String getFirstDayOfMonth(int year,int month){
-
Calendar cal = Calendar.getInstance();
-
//设置年份
-
cal.set(Calendar.YEAR,year);
-
//设置月份
-
cal.set(Calendar.MONTH, month-1);
-
//获取某月最小天数
-
int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
-
//设置日历中月份的最小天数
-
cal.set(Calendar.DAY_OF_MONTH, firstDay);
-
//格式化日期
-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
-
String firstDayOfMonth = sdf.format(cal.getTime());
-
return firstDayOfMonth;
-
}
-
-
/**
-
* 获得该月最后一天
-
* @param year
-
* @param month
-
* @return
-
*/
-
publicstatic String getLastDayOfMonth(int year,int month){
-
Calendar cal = Calendar.getInstance();
-
//设置年份
-
cal.set(Calendar.YEAR,year);
-
//设置月份
-
cal.set(Calendar.MONTH, month-1);
-
//获取某月最大天数
-
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
-
//设置日历中月份的最大天数
-
cal.set(Calendar.DAY_OF_MONTH, lastDay);
-
//格式化日期
-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
-
String lastDayOfMonth = sdf.format(cal.getTime());
-
return lastDayOfMonth;
-
}
-