首页 > 其他分享 >日期工具类,获取全年每月有几周,分别是多少,且每周对应的是几号到几号

日期工具类,获取全年每月有几周,分别是多少,且每周对应的是几号到几号

时间:2024-04-25 10:45:30浏览次数:24  
标签:return 每周 几周 range 几号 startTime date new endTime

一、概述

  项目需要做日程组件,其中涉及到了日历这块的内容。

  需求:

    1.获取全年有多少个月

    2.获取每月有多少个周

    3.获取每月每一天对应的是星期几

    4.单独获取某一天对应的是星期几

    5.把以上四条组织成为一个集合

二、代码示例

/**
 * 时间分割工具类
 */
public class DateSplitUtil {
    public static class DateBean {
        private String year;
        private String month;
        private String day;
        private String week;
    }

    private DateSplitUtil() {
        throw new IllegalStateException("请通过静态方法调用!");
    }

    public static String getFormatDay(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd", Locale.getDefault());
        Date date = new Date(timestamp);
        return sdf.format(date);
    }
    public static String getFormatDayYYYYMMDDHHMMSS(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date = new Date(timestamp);
        return sdf.format(date);
    }

    public static String getFormatDay(long timestamp, String formatStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr, Locale.getDefault());
        Date date = new Date(timestamp);
        return sdf.format(date);
    }

    public static DateBean getDataBean(String formatStr) {
        String[] datas = formatStr.split("-");
        DateBean bean = new DateBean();
        return bean;
    }

    /**
     * 当前年
     *
     * @return
     */
    public static int getCurrentYear() {
        return LocalDate.now().getYear();
    }

    /**
     * 当前月份
     *
     * @return
     */
    public static int getCurrentMonth() {
        return LocalDate.now().getMonthValue();
    }

    public static int getCurrentDay() {
        return LocalDate.now().getDayOfMonth();
    }

    public static int getCurrentHour() {
        return LocalDateTime.now().getHour();
    }

    public static int getCurrentMinute() {
        return LocalDateTime.now().getMinute();
    }

    /**
     * 获取每个月有多少天
     *
     * @param year  年
     * @param month 月
     * @return
     */
    public static int getMonthCount(int year, int month) {
        YearMonth yearMonth = YearMonth.of(year, month);
        // 获取该月份的天数
        int daysInMonth = yearMonth.lengthOfMonth();
        return daysInMonth;
    }

    public static String getWhichWeek(int year, int month, int day) {
        String weekStr = "";
        LocalDate date = LocalDate.of(year, month, day);
        // 获取该日期是周几
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        WeekEnum[] weeks = WeekEnum.values();
        for (WeekEnum week : weeks) {
            if (week.getWeekNum() == dayOfWeek.getValue()) {
                weekStr = week.getDescribe();
            }
        }
        return weekStr;
    }

    /**
     * 获取今天是周几
     * @return
     */
    public static WeekEnum getCurrentDayWhichWeek() {
        WeekEnum weekStr = WeekEnum.Monday;
        LocalDate date = LocalDate.of(getCurrentYear(), getCurrentMonth(), getCurrentDay());
        // 获取该日期是周几
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        WeekEnum[] weeks = WeekEnum.values();
        for (WeekEnum week : weeks) {
            if (week.getWeekNum() == dayOfWeek.getValue()) {
                weekStr = week;
            }
        }
        return weekStr;
    }


    /**
     * 获取今天的日期
     *
     * @return
     */
    public static String getTodayDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd", Locale.getDefault());
        Date date = new Date();
        return sdf.format(date);
    }

    public static String getTodayDayYYYYMMDD() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Date date = new Date();
        return sdf.format(date);
    }


    public static void getTodayStartTime() {
        LocalDate date = LocalDate.now(); // 假设使用今天的日期
        LocalDateTime startOfDay = LocalDateTime.of(date, LocalTime.MIDNIGHT); // 凌晨开始时间
        LocalDateTime endOfDay = LocalDateTime.of(date, LocalTime.MAX); // 凌晨结束时间

        KLog.e("getTodayStartTime:", date.toString() + " " + startOfDay.toLocalTime().getHour() + "" + startOfDay.toLocalTime().getMinute());
        KLog.e("getTodayStartTime:", date.toString() + " " + endOfDay.toLocalTime().getHour() + "" + endOfDay.toLocalTime().getMinute());
    }

//    public static String getTodayEndTime() {
//
//    }

    /**
     * 切分时间,并且获取切分后的时间段集合
     *
     * @param type      分割类型:按年、按月、按周、按日
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 切分后的时间段集合
     */
    public static List<DateRange> splitAndGetByType(int type, LocalDateTime startTime, LocalDateTime endTime) {
        if (type == 1) {
            // 按年切分
            return splitDateRangeByYear1(startTime, endTime);
        } else if (type == 2) {
            // 按月切分
            return splitDateRangeByMonth(startTime, endTime);
        } else if (type == 3) {
            // 按周切分
            return splitDateRangeByWeek(startTime, endTime);
        } else if (type == 4) {
            //按日切分
            return splitDateRangeByDay(startTime, endTime);
        } else if (type == 5) {
            //一次性
            List<DateRange> dateRangeList = new ArrayList<>();
            DateRange dateRange = new DateRange();
            dateRange.setBegin(startTime);
            dateRange.setEnd(endTime);
            dateRangeList.add(dateRange);
            return dateRangeList;
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 切分时间,并且获取某一轮的时间对象
     *
     * @param type      分割类型:按年、按月、按周、按日
     * @param turn      时间段(分割后的时间轮数,如将2021-10-01~2022-10-01,按月分割时,就能得到12轮时间段)
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 第turn段的时间对象
     */
    public static DateRange splitAndGetByTurn(int type, long turn, LocalDateTime startTime, LocalDateTime endTime) {
        //按年切分
        if (type == 1) {
            List<DateRange> dateRangeList = splitDateRangeByYear(startTime, endTime);
            return getRangeByTurn(dateRangeList, turn);
        } else if (type == 2) {
            // 按月切分
            List<DateRange> dateRangeList = splitDateRangeByMonth(startTime, endTime);
            return getRangeByTurn(dateRangeList, turn);
        } else if (type == 3) {
            // 按周切分
            List<DateRange> dateRangeList = splitDateRangeByWeek(startTime, endTime);
            return getRangeByTurn(dateRangeList, turn);
        } else if (type == 4) {
            //按日切分
            List<DateRange> dateRangeList = splitDateRangeByDay(startTime, endTime);
            return getRangeByTurn(dateRangeList, turn);
        } else if (type == 5) {
            //一次性
            DateRange dateRange = new DateRange();
            dateRange.setBegin(startTime);
            dateRange.setEnd(endTime);
            return dateRange;
        } else {
            return new DateRange();
        }
    }


    /**
     * 按年分割
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 分割后的时间段集合
     */
    private static List<DateRange> splitDateRangeByYear(LocalDateTime startTime, LocalDateTime endTime) {
        long seconds = startTime.until(endTime, ChronoUnit.SECONDS);
        if (seconds <= 0) {
            return new ArrayList<>();
        }
        //轮数
        long turnNum = 0;
        //分割的时间段集合,使用累加算法
        List<DateRange> dateList = new ArrayList<>();
        DateRange range = new DateRange();
        range.setBegin(startTime);
        while (true) {
            turnNum++;
            //年份相等,不再累加
            if (startTime.getYear() == endTime.getYear()) {
                range.setEnd(endTime);
                range.setTurnNum(turnNum);
                dateList.add(range);
                break;
            }
            //将时间调整为该年的第一天 0时 0分 0秒
            startTime = LocalDateTime.of(LocalDate.from(startTime.with(TemporalAdjusters.firstDayOfYear()).plusYears(1)), LocalTime.MIN);
            LocalDateTime tmpBegin = startTime;
            //计算出上一天的最后一秒
            LocalDateTime endDate = tmpBegin.minusSeconds(1);
            range.setEnd(endDate);
            range.setTurnNum(turnNum);
            dateList.add(range);
            //创建新的时间段
            range = new DateRange();
            range.setBegin(tmpBegin);
        }
        return dateList;
    }

    /**
     * 按月分割
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 分割后的时间段集合
     */
    private static List<DateRange> splitDateRangeByMonth(LocalDateTime startTime, LocalDateTime endTime) {

        long seconds = startTime.until(endTime, ChronoUnit.SECONDS);
        if (seconds <= 0) {
            return new ArrayList<>();
        }
        //轮数
        long turnNum = 0;
        //分割的时间段集合,使用累加算法
        List<DateRange> dateList = new ArrayList<>();
        DateRange range = new DateRange();
        range.setBegin(startTime);
        while (true) {
            turnNum++;
            startTime = startTime.plusMonths(1);
            //大于截止日期时,不再累加
            if (startTime.isAfter(endTime)) {
                range.setEnd(endTime);
                range.setTurnNum(turnNum);
                dateList.add(range);
                break;
            }
            //将时间调整为当前月的第一天的 0时 0分 0秒
            startTime = LocalDateTime.of(LocalDate.from(startTime.with(TemporalAdjusters.firstDayOfMonth())), LocalTime.MIN);
            LocalDateTime tmpBegin = startTime;
            //计算出上一天的最后一秒
            LocalDateTime endDate = tmpBegin.minusSeconds(1);
            range.setEnd(endDate);
            range.setTurnNum(turnNum);
            dateList.add(range);
            //创建新的时间段
            range = new DateRange();
            range.setBegin(tmpBegin);
        }
        return dateList;
    }

    /**
     * 按年分割
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 分割后的时间段集合
     */
    private static List<DateRange> splitDateRangeByYear1(LocalDateTime startTime, LocalDateTime endTime) {
        long seconds = startTime.until(endTime, ChronoUnit.SECONDS);
        if (seconds <= 0) {
            return new ArrayList<>();
        }
        //轮数
        long turnNum = 0;
        //分割的时间段集合,使用累加算法
        List<DateRange> dateList = new ArrayList<>();
        DateRange range = new DateRange();
        range.setBegin(startTime);
        while (true) {
            turnNum++;
            //年份相等,不再累加
            if (range.getBegin().getYear() == endTime.getYear()) {
                range.setEnd(endTime);
                range.setTurnNum(turnNum);
                dateList.add(range);
                break;
            }
            LocalDateTime tmpBegin = range.getBegin();
            startTime = tmpBegin;
            //计算出上一天的最后一秒
            LocalDateTime endDate = tmpBegin.plusYears(1).minusDays(1);
            if (endDate.getYear() == endTime.getYear() && endDate.getMonth() != endTime.getMonth() && endDate.getDayOfYear() == endTime.getDayOfYear()) {
                range.setEnd(endTime);
                range.setTurnNum(turnNum);
                dateList.add(range);
                break;
            }
            range.setEnd(endDate);
            range.setTurnNum(turnNum);
            dateList.add(range);
            //创建新的时间段
            range = new DateRange();
            range.setBegin(endDate.plusDays(1));
            //如果上一次结束的时间大于当前传入的开始时间跳出
            Date inendTime = Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant());
            Date newstartTime = Date.from(range.getBegin().atZone(ZoneId.systemDefault()).toInstant());
            if (isBeforeDate(newstartTime, inendTime)) {
                break;
            }
        }
        return dateList;
    }

    /**
     * 按周分割
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 分割后的时间段集合
     */
    private static List<DateRange> splitDateRangeByWeek(LocalDateTime startTime, LocalDateTime endTime) {
        long seconds = startTime.until(endTime, ChronoUnit.SECONDS);
        if (seconds <= 0) {
            return new ArrayList<>();
        }
        //轮数
        long turnNum = 0;
        //分割的时间段集合,使用累加算法
        List<DateRange> dateList = new ArrayList<>();
        DateRange range = new DateRange();
        range.setBegin(startTime);
        while (true) {
            turnNum++;
            startTime = startTime.plusWeeks(1);
            //大于截止日期时,不再累加
            if (startTime.isAfter(endTime)) {
                range.setEnd(endTime);
                range.setTurnNum(turnNum);
                dateList.add(range);
                break;
            }
            //将时间调整为该周第一天的 0时 0分 0秒
            startTime = LocalDateTime.of(LocalDate.from(startTime.with(DayOfWeek.MONDAY)), LocalTime.MIN);
            LocalDateTime tmpBegin = startTime;
            //计算出上一天的最后一秒
            LocalDateTime endDate = tmpBegin.minusSeconds(1);
            range.setEnd(endDate);
            range.setTurnNum(turnNum);
            dateList.add(range);
            //创建新的时间段
            range = new DateRange();
            range.setBegin(tmpBegin);
        }
        return dateList;
    }

    /**
     * 按日分割
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 分割后的时间段集合
     */
    private static List<DateRange> splitDateRangeByDay(LocalDateTime startTime, LocalDateTime endTime) {
        long seconds = startTime.until(endTime, ChronoUnit.SECONDS);
        if (seconds < 0) {
            return new ArrayList<>();
        }
        //轮数
        long turnNum = 0;
        //分割的时间段集合,使用累加算法
        List<DateRange> dateList = new ArrayList<>();
        DateRange range = new DateRange();
        range.setBegin(startTime);
        while (true) {
            turnNum++;
            startTime = startTime.plusDays(1);
            //大于截止日期时,不再累加
            if (startTime.isAfter(endTime)) {
                range.setEnd(endTime);
                range.setTurnNum(turnNum);
                dateList.add(range);
                break;
            }
            //将时间调整为该天的 0时 0分 0秒
            startTime = LocalDateTime.of(startTime.getYear(), startTime.getMonth(), startTime.getDayOfMonth(), 0, 0, 0);
            LocalDateTime tmpBegin = startTime;
            //计算出上一天的最后一秒
            LocalDateTime endDate = tmpBegin.minusSeconds(1);
            range.setEnd(endDate);
            range.setTurnNum(turnNum);
            dateList.add(range);
            //创建新的时间段
            range = new DateRange();
            range.setBegin(tmpBegin);
        }
        return dateList;
    }

    /**
     * 根据时间段(分割后的时间轮数,2021-10-01~2022-10-01,按月分隔时就有12轮时间段)获取时间范围
     *
     * @param dateRangeList 分隔后的时间段集合
     * @param turn          轮次,当前时间处于第几段
     * @return 时间对象
     */
    private static DateRange getRangeByTurn(List<DateRange> dateRangeList, long turn) {
        DateRange dateRange = new DateRange();
        for (DateRange d : dateRangeList) {
            if (d.getTurnNum() == turn) {
                dateRange = d;
            }
        }
        return dateRange;
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间,注意三个参数的时间格式要一致
     * * @param nowTime
     * * @param startTime
     * * @param endTime
     * * @return 在时间段内返回true,不在返回false
     **/

    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(begin) && date.before(end);
    }

    public static boolean isBeforeDate(Date nowTime, Date endTime) {
        if (nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(end);
    }

    /**
     * 月底时间处理工具类
     */
    public static String downdate() throws ParseException {
        //1.获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        Date nowTime;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 1));
        if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
            //返回本月
            Calendar cale = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String now1 = sdf.format(new Date());
            cale.setTime(formatter.parse(now1));
            cale.add(Calendar.MONTH, 1);
            cale.set(Calendar.DAY_OF_MONTH, 0);
            String lastDayOfMonth = formatter.format(cale.getTime());
            return lastDayOfMonth;
        } else {
            //返回上月末
            Calendar cale = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String now1 = sdf.format(new Date());
            cale.setTime(formatter.parse(now1));
            cale.add(Calendar.MONTH, 0);
            cale.set(Calendar.DAY_OF_MONTH, 0);
            String lastDayOfMonth = formatter.format(cale.getTime());
            return lastDayOfMonth;
        }
        //2.判断当前时间是否本月底 是返回本月底 不是返回上月底
    }

    public static String getChinaDateFromString(String str) {
        try {
            if (str == null) {
                return getChinaCurrentDate();
            }
            str = str.trim();
            int year = 0;
            int month = 0;
            int day = 0;
            //System.out.println("==="+str);
            if (str == null || str.equals("null") || str.equals("")) {
                return getChinaCurrentDate();
            } else if (str.indexOf("年") > 0 || str.indexOf("月") > 0 || str.indexOf("日") > 0) {
                return str;
            } else {
                if (str.length() == 10 && (str.indexOf("-") > 0)) {
                    // by meconsea  add str.indexOf("-") > 0
                    year = Integer.parseInt(str.substring(0, 4));
                    month = Integer.parseInt(str.substring(5, 7));
                    day = Integer.parseInt(str.substring(8, 10));
                } else if (str.length() == 8) {
                    year = Integer.parseInt(str.substring(0, 4));
                    month = Integer.parseInt(str.substring(4, 6));
                    day = Integer.parseInt(str.substring(6, 8));
                } else if (str.length() == 6) {
                    year = Integer.parseInt(str.substring(0, 4));
                    month = Integer.parseInt(str.substring(4, 6));
                }
                if (day == 0) {
                    str = year + "年" + month + "月";
                } else {
                    str = year + "年" + month + "月" + day + "日";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String getChinaCurrentDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String str_date = dateFormat.format(Calendar.getInstance().getTime());
        str_date = str_date.substring(0, 4) + "年" + str_date.substring(4, 6) + "月" +
                str_date.substring(6, 8) + "日 ";
        return str_date;
    }

    /***
     * 获取系统当前时间
     */
    public static String getNowTime(int type) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String now = sdf.format(new Date());
        Date nowTime = sdf.parse(now);
        String now1 = sdf1.format(new Date());
        Date nowTime1 = sdf1.parse(now);
        if (type == 1) {
            // yyyy-MM-dd HH:mm:ss
            return String.valueOf(now);
        } else {
            // yyyy-MM-dd
            return String.valueOf(now1);
        }
    }

    /***
     * 字符串形式日期 补月初神操作 yyyy-MM  转yyyy-MM-dd
     * @param dateTime
     */
    public static String addDayTime(String dateTime) {
        String newDateTime = null;
        if (dateTime.length() == 7) {
            newDateTime = dateTime + "-01";
        }
        return newDateTime;
    }

    /***
     * 统一时间格式处理工具类
     * 均统一为yyyy-MM-dd形式
     * 目前数据中存在的形式有 yyyy-MM-dd yyyy.MM.dd  yyyy/MM/dd  yyyy.MM (yyyy年MM月)暂时不处理
     */
    public static String strToDate(String date) throws ParseException {
        String newTime = null;
        if (date != null) {
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            if (date.contains("-")) {
                if (date.length() <= 7) {
                    newTime = DateSplitUtil.addDayTime(date);
                } else {
                    newTime = simpleDateFormat1.format(simpleDateFormat1.parse(date));
                    ;
                }
            } else if (date.contains(".")) {
                int count = (date.length() - date.replace(".", "").length());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM");
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy.MM.dd");
                if (date.length() <= 7 && count == 1) {
                    newTime = simpleDateFormat1.format(simpleDateFormat.parse(date));
                } else {
                    newTime = simpleDateFormat1.format(simpleDateFormat2.parse(date));
                }
            } else if (date.contains("/")) {
                int count = (date.length() - date.replace("/", "").length());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM");
                SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy/MM/dd");
                if (date.length() <= 7 && count == 1) {
                    newTime = simpleDateFormat1.format(simpleDateFormat.parse(date));
                } else {
                    newTime = simpleDateFormat1.format(simpleDateFormat3.parse(date));
                }
            }
        }
        return newTime;
    }

    public static List<List<LocalDate>> partitionCalendar(int year) {
        List<List<LocalDate>> workWeeks = new ArrayList<>();
        int dayOfYear = Year.of(year).length(); // 获取指定年份的总天数

        LocalDate startDate = LocalDate.of(year, Month.JANUARY, 1);
        LocalDate endDate = LocalDate.of(year, Month.DECEMBER, 31);

        // 划分工作周
        List<LocalDate> week = new ArrayList<>();
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
            week.add(date);

            // 判断是否为工作周的最后一天
            if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfYear() == dayOfYear) {
                workWeeks.add(week);
                week = new ArrayList<>();
            }
        }

        return workWeeks;
    }


    /**
     * 获取本月的第几周
     *
     * @return
     */
    public static int getWeekNumber() {
        return 0;
    }

    public static List<WorkDay> partitionCalendar(int year, int month) {
        List<WorkDay> workDays = new ArrayList<>();
        YearMonth yearMonth = YearMonth.of(year, month);

        LocalDate startDate = yearMonth.atDay(1);
        LocalDate endDate = yearMonth.atEndOfMonth();

        // 划分工作日
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
            DayOfWeek dayOfWeek = date.getDayOfWeek();

            // 判断是否为工作日(周一到周五)
            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
                int week = date.get(WeekFields.of(DayOfWeek.MONDAY, 1).weekOfMonth()); // 获取是本月的第几周
                workDays.add(new WorkDay(date, String.valueOf(week)));
            }
        }

        return workDays;
    }

    static class WorkDay {
        private LocalDate date;
        private String week;

        public WorkDay(LocalDate date, String week) {
            this.date = date;
            this.week = week;
        }

        public LocalDate getDate() {
            return date;
        }

        public String getWeek() {
            return week;
        }
    }


    public static List<Week> generateWeeklyCalendar(int year, int month) {
        List<Week> weeklyCalendar = new ArrayList<>();
        YearMonth yearMonth = YearMonth.of(year, month);

        LocalDate startDate = yearMonth.atDay(1);
        LocalDate endDate = yearMonth.atEndOfMonth();

        int weekNumber = 1;
        List<LocalDate> dates = new ArrayList<>();
        for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
            dates.add(date);

            // 如果是周日,则表示一个完整的周结束,创建一个新的周
            if (date.getDayOfWeek() == DayOfWeek.SUNDAY) {
                weeklyCalendar.add(new Week(weekNumber, new ArrayList<>(dates)));
                dates.clear();
                weekNumber++;
            }
        }

        // 处理最后一周不满一周的情况
        if (!dates.isEmpty()) {
            weeklyCalendar.add(new Week(weekNumber, dates));
        }

        return weeklyCalendar;
    }



    public static void main(String[] args) {
        int year = 2024; // 指定年份
        Map<Integer, List<Week>> yearlyCalendar = generateYearlyCalendar(year);
        // 输出每个月的周日历
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int month : yearlyCalendar.keySet()) {
            System.out.println("Month " + month + ":");
            List<Week> weeklyCalendar = yearlyCalendar.get(month);
            for (Week week : weeklyCalendar) {
                System.out.println("  Week " + week.getWeekNumber() + ":");
                //判断weeklyCalendar.get(0).size是否等于7  不等于的话从上一期上不全
                // 1.不是1月的话拿上一个月的最后一月的最后一星期的数据顺序追加到最前面
                // 2.1月份的话需要拿上一年最后一月最后一星期的数据来补全

                //判断weeklyCalendar.get((weeklyCalendar.size))不足七天的话舍弃
                int last = weeklyCalendar.size() - 1;
//                if(weeklyCalendar.get(last).dates.size() < 7){
//                    weeklyCalendar.remove(last);
//                }
                for (LocalDate date : week.getDates()) {
                    System.out.print("    " + formatter.format(date) + " ");
                }
                System.out.println();
            }
        }
    }

    public static Map<Integer, List<Week>> generateYearlyCalendar(int year) {
        Map<Integer, List<Week>> yearlyCalendar = new TreeMap<>();

        for (int month = 1; month <= 12; month++) {
            YearMonth yearMonth = YearMonth.of(year, month);

            LocalDate startDate = yearMonth.atDay(1);
            LocalDate endDate = yearMonth.atEndOfMonth();

            int weekNumber = 1;
            List<Week> weeklyCalendar = new ArrayList<>();
            List<LocalDate> dates = new ArrayList<>();
            for (LocalDate date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
                dates.add(date);

                // 如果是周日,则表示一个完整的周结束,创建一个新的周
                if (date.getDayOfWeek() == DayOfWeek.SUNDAY) {
                    weeklyCalendar.add(new Week(weekNumber, new ArrayList<>(dates)));
                    dates.clear();
                    weekNumber++;
                }
            }

            // 处理最后一周不满一周的情况
            if (!dates.isEmpty()) {
                weeklyCalendar.add(new Week(weekNumber, dates));
            }

            yearlyCalendar.put(month, weeklyCalendar);
        }

        return yearlyCalendar;
    }

    public static class Week {
        private int weekNumber;
        private List<LocalDate> dates;

        public Week(int weekNumber, List<LocalDate> dates) {
            this.weekNumber = weekNumber;
            this.dates = dates;
        }

        public int getWeekNumber() {
            return weekNumber;
        }

        public List<LocalDate> getDates() {
            return dates;
        }
    }

    public static class DateRange {
        public DateRange() {
        }

        LocalDateTime begin;
        LocalDateTime end;
        long turnNum;

        public LocalDateTime getBegin() {
            return begin;
        }

        public void setBegin(LocalDateTime begin) {
            this.begin = begin;
        }

        public LocalDateTime getEnd() {
            return end;
        }

        public void setEnd(LocalDateTime end) {
            this.end = end;
        }

        public long getTurnNum() {
            return turnNum;
        }

        public void setTurnNum(long turnNum) {
            this.turnNum = turnNum;
        }
    }
}

 

标签:return,每周,几周,range,几号,startTime,date,new,endTime
From: https://www.cnblogs.com/tony-yang-flutter/p/18157059

相关文章

  • 【每周例题】力扣 C++ 分割字符串
    分割字符串题目 题目分析1.先确定用容器存储,容器的存储结构如下图所示: 2.这个题目的话,第一反应应该是用到动态规划,下面是动态规划的模板:res=[]ans=[]defbacktrack(未探索区域,res,path):if未探索区域满足结束条件:res.add(ans)#深度拷贝......
  • 【每周例题】力扣 C++ 最小和分割
    最小和分割题目 题目分析1.num1 和 num2 中所有数字出现的次数之和等于 num 中所有数字出现的次数。即,num1与num2是从num中提取出来的,且不会重复提取同一个数字,且提取的顺序并不需要按照num的数字顺序2.返回 num1 和 num2 可以得到的和的最小值。要想得到最小值,需......
  • Peaks:每周至少要进行一次用户访谈?
    名字:Peaks开发者/团队:VogelhausAppsGmbH平台:iOS、watchOS请简要介绍下这款产品每个人生活的节奏都有一个内置的生理时钟,这就是所谓的昼夜节律。它不仅控制着我们何时感到疲倦或者精力旺盛,更加深远的意义在于,理解自己的昼夜节律可以帮助你发挥身体的最大潜能,从而让你更高......
  • 【每周例题】力扣 C++ 移除元素
    移除元素题目移除元素 思路分析1.涉及到容器,那么就很直接的想法,遍历容器,找出与val相同的数,移除,然后利用函数输出长度与移除后的数组2.移除部分我们使用指针去处理,用指针遍历数组,符合移除条件的利用erase函数移除注:这里使用到了一个万能头文件,参加蓝桥杯的同学可以试试运用......
  • 【每周例题】蓝桥杯 C++ 多数
    多数元素题目多数元素思路分析一.第一个想法,暴力遍历,然后会发现容易超时,那么更进一步想:哈希表使用哈希表存储每个数出现的次数,即使用哈希映射(HashMap)来存储每个元素以及出现的次数。对于哈希映射中的每个键值对,键表示一个元素,值表示该元素出现的次数加入后,遍历所有键值对,......
  • 【每周例题】蓝桥杯 C++ 对称排序
    对称排序题目对称排序 题目分析1.因为数字是对称交换,所以我们只需要判断前n/2项需不需要交换就好了2.这里我采用了升序排序,你们也可以尝试降序排序3.我们只需要排序好后再遍历一下整个数组,找出不符合排序的就输出NO就好了代码#include<iostream>#include<bits/stdc+......
  • 利用Java实现每周二上午十点定时调用接口的方法
    摘要:在软件开发中,定时任务是一项常见的需求,特别是需要定期执行一些特定操作的场景。本文将介绍如何利用Java编程语言实现每周二上午十点定时调用接口的功能。通过使用Java中的定时任务调度工具,我们可以轻松地实现这一功能,从而满足各种业务需求。正文:在Java中实现定时任务......
  • 【每周例题】蓝桥杯 C++ 鸡哥的蛋糕大作战
    鸡哥的蛋糕大作战题目鸡哥的蛋糕大作战 题目分析1.使用一个for循环遍历全数,寻找最大洞的数2.使用一个while进行数位拆分,寻找洞的数量3.使用if从两个条件寻找最大洞的最小数符合最大洞的数洞数相同中的最小数代码#include<iostream>#include<bits/stdc++.h>using......
  • 【每周例题】蓝桥杯 C++ 鸡哥的奇特密码
    鸡哥的奇特密码题目鸡哥的奇特密码 题目分析 1.首先,我们需要想到用一个for循环去遍历整个数组,用if寻找出需要我们处理的部分2.如何处理:将重复的L丢出数组,可以运用pop_back()函数3.为了避免越界,我们可以从后往前遍历代码#include<iostream>#include<bits/stdc++.h>u......
  • 机器学习每周挑战——旅游景点数据分析
    数据的截图,数据的说明:#字段数据类型#城市string#名称string#星级string#评分float#价格float#销量int#省/市/区string#坐标string#简介string#是否免费bool#具体地址string拿到数据第一步我们先导入数据......