- 首先获取现在的日期
- 根据现在的日期进行判断获取第一天和最后一天
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String startDay = df.format(new Date());
Calendar calendar = Calendar.getInstance();
calendar.set(Integer.parseInt(startDay.substring(0,4)), Integer.parseInt(startDay.substring(5,7)) - 1, 1);
String firstDayOfMonth = new SimpleDateFormat( "yyyy-MM-dd ").format(calendar.getTime());
System.out.println("第一天:"+firstDayOfMonth);
//这里先设置要获取月份的下月的第一天
calendar.set(Integer.parseInt(startDay.substring(0,4)), Integer.parseInt(startDay.substring(5,7)), 1);
//这里将日期值减去一天,从而获取到要求的月份最后一天
calendar.add(Calendar.DATE, -1);
String lastDayOfMonth = new SimpleDateFormat( "yyyy-MM-dd ").format(calendar.getTime());
System.out.println("最后一天:"+lastDayOfMonth);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("上个月第一天:"+format.format(calendar.getTime()));
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar1=Calendar.getInstance();
int month=calendar1.get(Calendar.MONTH);
calendar1.set(Calendar.MONTH, month-1);
calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println("上个月最后一天:"+sf.format(calendar1.getTime()));