测试
public static void main(String[] args) {SimpleDateFormat sdf = new SimpleDateFormat("MM");String format = sdf.format(new Date());int month = Integer.parseInt(format);System.out.println(month);String firstDayOfMonth = getFirstDayOfMonth(month);System.out.println(month+"月第一天:"+firstDayOfMonth);String lastDayOfMonth = getLastDayOfMonth(month);System.out.println(month+"月的最后一天:"+ lastDayOfMonth);}
11月第一天:-11-01 00:00:0011月的最后一天:-11-30 23:59:59
获取第一天
/*** 获取当前月第一天* @param month* @return*/public static String getFirstDayOfMonth(int month) {Calendar calendar = Calendar.getInstance();// 设置月份calendar.set(Calendar.MONTH, month - 1);// 获取某月最小天数int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);// 设置日历中月份的最小天数calendar.set(Calendar.DAY_OF_MONTH, firstDay);// 格式化日期SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String firstDayDate = sdf.format(calendar.getTime())+" 00:00:00";return firstDayDate;}
获取最后一天
/*** 获取当前月最后一天* @param month* @return*/public static String getLastDayOfMonth(int month) {Calendar calendar = Calendar.getInstance();// 设置月份calendar.set(Calendar.MONTH, month - 1);// 获取某月最大天数int lastDay=0;//2月的平年瑞年天数if(month==2) {// 这个api在计算2月的过程中有问题lastDay = calendar.getLeastMaximum(Calendar.DAY_OF_MONTH);}else {lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);}// 设置日历中月份的最大天数calendar.set(Calendar.DAY_OF_MONTH, lastDay);// 格式化日期SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String lastDayDate = sdf.format(calendar.getTime())+" 23:59:59";return lastDayDate;}
如果觉得《java 获取当前月的第一天和最后一天》对你有帮助,请点赞、收藏,并留下你的观点哦!