package date; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 获取给定年月计算当月有几周,每周的开始和结束日期 * @author pei * */ public class TestLocal { static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); public static void main(String[] args) { List<Map> list = getScope(); System.out.println("list====="+list); } public static List<Map> getScope() { String date = "2023-01-01"; String timeStrs[] = date.split("-"); Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, Integer.parseInt(timeStrs[0])); c.set(Calendar.MONTH, Integer.parseInt(timeStrs[1]) - 1); c.setFirstDayOfWeek(Calendar.MONDAY); int weeks = c.getActualMaximum(Calendar.WEEK_OF_MONTH); LocalDate localDateate = LocalDate.parse(date, dateTimeFormatter); //月份第一周的起始时间和结束时间 LocalDate firstDay = localDateate.with(TemporalAdjusters.firstDayOfMonth()); String firstDayStr = firstDay.format(dateTimeFormatter); String sunStr = getSunOfWeek(firstDayStr); List<Map> weekInfos = new ArrayList<>(); for (int i = 1; i <= weeks; i++) { Map weekInfo = new HashMap(); //第一周的起始时间就是当月的1号,结束时间就是周日 if (i == 1) { weekInfo.put("start",firstDayStr); weekInfo.put("end",sunStr); weekInfo.put("order",i); //计算接下来每周的周一和周日 } else if (i < weeks) { //由于sunStr是上一周的周日,所以取周一要取sunStr的下一周的周一 String monDay = getLastMonOfWeek(sunStr); sunStr = getSunOfWeek(monDay); weekInfo.put("start",monDay); weekInfo.put("end",sunStr); weekInfo.put("order",i); //由于最后一周可能结束时间不是周日,所以要单独处理 } else { String monDay = getLastMonOfWeek(sunStr); //结束时间肯定就是当前月的最后一天 LocalDate lastDay = localDateate.with(TemporalAdjusters.lastDayOfMonth()); String endDay = lastDay.format(dateTimeFormatter); weekInfo.put("start",monDay); weekInfo.put("end",endDay); weekInfo.put("order",i); } weekInfos.add(weekInfo); } return weekInfos; } //算出所在周的周日 public static String getSunOfWeek(String time) { LocalDate localDateate = LocalDate.parse(time, dateTimeFormatter); LocalDate endday = localDateate.with(TemporalAdjusters.next(java.time.DayOfWeek.MONDAY)).minusDays(1); String endDayStr = endday.format(dateTimeFormatter); return endDayStr; } //下一周的周一 public static String getLastMonOfWeek(String time) { LocalDate localDateate = LocalDate.parse(time, dateTimeFormatter); LocalDate endday = localDateate.with(TemporalAdjusters.next(java.time.DayOfWeek.MONDAY)); String endDayStr = endday.format(dateTimeFormatter); return endDayStr; } }
标签:java,String,几周,给定,util,当月,import,Calendar,LocalDate From: https://www.cnblogs.com/xianz666/p/17101078.html