java中如何得到上一个的月第一天与最后一天。(不以当前日期为标准)
发布网友
发布时间:2022-04-27 05:41
我来回答
共1个回答
热心网友
时间:2022-05-19 13:26
Calendar calendar = Calendar.getInstance();
//得到月初
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date strDateFrom = calendar.getTime();
//得到月末
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date strDateTo = calendar.getTime();
或者
public static String getMonthFirstDay() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar
.getActualMinimum(Calendar.DAY_OF_MONTH));
return dateFormat("yyyy-MM-dd", calendar.getTime());
}
/**
* 得到本月的最后一天
*
* @return
*/
public static String getMonthLastDay() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar
.getActualMaximum(Calendar.DAY_OF_MONTH));
return dateFormat("yyyy-MM-dd", calendar.getTime());
}
或者
private int getLastDayOfMonth(int year, int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
// 某年某月的最后一天
return cal.getActualMaximum(Calendar.DATE);
}
需要注意的是:资料均来自JAVAEYE ....月份是从0开始的,比如说如果输入5的话,实际上显示的是4月份的最后一天,千万不要搞错了哦