日期处理

根据月份得到这个月份的最后一天

 

public  String getLastDayOfMonth(String yearMonth) {
int year = Integer.parseInt(yearMonth.split("-")[0]); //年
int month = Integer.parseInt(yearMonth.split("-")[1]); //月
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);
// 格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(cal.getTime());
}

//月份之间的月份
public  List<String> getMonthBetween(String minDate, String maxDate) throws ParseException {
ArrayList<String> result = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月

Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();

min.setTime(sdf.parse(minDate));
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

max.setTime(sdf.parse(maxDate));
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

Calendar curr = min;
while (curr.before(max)) {
result.add(sdf.format(curr.getTime()));
curr.add(Calendar.MONTH, 1);
}

return result;
}

posted on 2021-05-10 14:28  陌离莫离  阅读(52)  评论(0编辑  收藏  举报

导航