java获取当月的第一天或最后一天
方式共有两种,使用java.util.Calendar日历类实现
第一种:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); //获得本月第一天 calendar.add(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, 1); String firstDay = sdf.format(calendar.getTime()); System.out.println("firstDay:"+ firstDay); //获得本月最后一天 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); String lastDay = sdf.format(calendar.getTime());
第二种:
Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.set(Calendar.DAY_OF_MONTH, 1); System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())); cal.roll(Calendar.DAY_OF_MONTH, -1); System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
参考文章:https://www.cnblogs.com/dongming-03/p/5628947.html