Java获取最后一天误区
下面是公司获取最后一天的工具代码,可把我坑惨了。
public static Date getLastDateOfMonth(int year, int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
int lastDay = cal.getActualMaximum(Calendar.DATE);
cal.set(Calendar.DAY_OF_MONTH, lastDay);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
Date date = cal.getTime();
return date;
}
Date lastDay1 = DateUtil.getLastDateOfMonth(2019,11); 得出12-31号,错误
用上述方法调用一下,结果11月最后一天是31号,我靠,无情。
下面这个才是能获取的。
cal.set(Calendar.DATE, 1);
cal.roll(Calendar.DATE, -1);
int lastDay = cal.get(Calendar.DATE);
参考: https://blog.csdn.net/myblogzz/article/details/79926146