Java gets the date range of each week of the specified year

Demand scenario:

简述项目相关背景:接到项目组需求,给定年份,返回对应该年份所有周的日期范围


code:

Idea: Step by step, from the first week to the last week, and finally return the list, the size of the list is the total number of weeks in the year

public class YearWeeksUtil {
    
    

    public static final String START_TIME = "startTime";
    public static final String END_TIME = "endTime";

    /**
     * 获取某年某周的时间跨度
     *
     * @param year 年份
     * @param week 周数
     * @return k-v
     */
    public static Map<String, String> getWeekRangeMap(int year, int week) {
    
    
        Map<String, String> dateMap = new HashMap<>(8);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        // 设置星期一为一周开始的第一天
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        // 可以不用设置
        calendar.setMinimalDaysInFirstWeek(4);
        // 获得当前的年
        int weekYear = calendar.get(Calendar.YEAR);
        // 获得指定年的第几周的开始日期(星期几)
        calendar.setWeekDate(weekYear, week, Calendar.MONDAY);
        Date time = calendar.getTime();
        String startTime = new SimpleDateFormat(DateUtils.YYYY_MM_DD).format(time);
        dateMap.put(START_TIME, startTime);
        // 获得指定年的第几周的结束日期(星期几)
        calendar.setWeekDate(weekYear, week, Calendar.SUNDAY);
        time = calendar.getTime();
        String endTime = new SimpleDateFormat(DateUtils.YYYY_MM_DD).format(time);
        dateMap.put(END_TIME, endTime);
        return dateMap;
    }

    /**
     * 获取某年有多少周
     *
     * @param year 年份
     * @return 当前年份的总周数
     */
    public static int getYearWeekCount(int year) {
    
    
        int week = 52;
        try {
    
    
            Map<String, String> timeMap = getWeekRangeMap(year, 53);
            if (!CollectionUtils.isEmpty(timeMap)) {
    
    
                String startTime = timeMap.get(START_TIME);
                if (startTime.substring(0, 4).equals(year + "")) {
    
    
                    // 判断年度是否相符,如果相符说明有53个周。
                    week = 53;
                }
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return week;
    }

    /**
     * 获取某年所有周的日期跨度
     *
     * @param year 年份
     * @return list 当前年份所有周的日期范围
     */
    public static List<Map<String, String>> getYearWeekMap(int year) {
    
    
        int weeks = getYearWeekCount(year);
        List<Map<String, String>> yearWeekMap = new ArrayList<>();
        for (int i = 1; i <= weeks; i++) {
    
    
            Map<String, String> dateMap = getWeekRangeMap(year, i);
            yearWeekMap.add(dateMap);
        }
        return yearWeekMap;
    }

}

postman test:

insert image description here

Guess you like

Origin blog.csdn.net/qq_40436854/article/details/123853532