java 给定日期获取当月每周开始时间和结束时间

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;

public class TestLocal1 {
  public static void main(String[] args) {
	  System.out.println("getScope()===="+getScope());
  }
  
	private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	public static List<Map> getScope() {
      String date = "2023-02-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(java.time.DayOfWeek.MONDAY);
      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 {
              //由于sunStr是上一周的周日,所以取周一要取sunStr的下一周的周一
              String monDay = getLastMonOfWeek(sunStr);
              sunStr = getSunOfWeek(monDay);
              weekInfo.put("start",monDay);
              weekInfo.put("end",sunStr);
              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;
  }

}

  

 

posted @ 2023-02-16 18:04  红尘沙漏  阅读(758)  评论(0编辑  收藏  举报