java Calendar Date 获取指定日期所在月或年的第一天和最后一天
一.获取传入日期所在月的第一天
public static Date getFirstDayDateOfMonth(final Date date) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); final int last = cal.getActualMinimum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, last); return cal.getTime(); }
二.获取传入日期所在月的最后一天
public static Date getLastDayOfMonth(final Date date) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, last); return cal.getTime(); }
三.获取传入日期所在年的第一天
public static Date getFirstDayDateOfYear(final Date date) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); final int last = cal.getActualMinimum(Calendar.DAY_OF_YEAR); cal.set(Calendar.DAY_OF_YEAR, last); return cal.getTime(); }
四.获取传入日期所在年的最后一天
public static Date getLastDayOfYear(final Date date) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); final int last = cal.getActualMaximum(Calendar.DAY_OF_YEAR); cal.set(Calendar.DAY_OF_YEAR, last); return cal.getTime(); }
五.获取指定年月的第一天
/** * 获取指定年月的第一天 * @param year * @param month * @return */ public static String getFirstDayOfMonth1(int year, int month) { Calendar cal = Calendar.getInstance(); //设置年份 cal.set(Calendar.YEAR, year); //设置月份 cal.set(Calendar.MONTH, month-1); //获取某月最小天数 int firstDay = cal.getMinimum(Calendar.DATE); //设置日历中月份的最小天数 cal.set(Calendar.DAY_OF_MONTH,firstDay); //格式化日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(cal.getTime()); }
六.传入年和月,获取到本月的最后一天
/** * 获取指定年月的最后一天 * @param year * @param month * @return */ public static String getLastDayOfMonth1(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); //格式化日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(cal.getTime()); }