天天看点

计算从指定日期开始的第几周的周几的日期

项目场景:

拿到的排课表数据,里面没有具体日期,而是第几周,周几的形式,需要转换成具体日期。

问题描述

其中的周几是从周一开始的,从1 到7,转换时也是按这个顺序来

原因分析:

解决方案:

/**
     * 获取指定日期所在周的周一日期
     * 从周一到周日
     * @param dateStr
     * @return
     */
    @Override
    public String getMondayDate(String dateStr) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(simpleDateFormat.parse(dateStr));

        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if (week == 1) {
            week = 7;
        } else {
            week -= 1;
        }
        calendar.add(Calendar.DAY_OF_MONTH, 1 - week);

        return simpleDateFormat.format(calendar.getTime());
    }

    /**
     * 获取从指定日期开始的第几周的周几的具体日期
     * @param beginDateStr
     * @param djz
     * @param zj 周1=1...周日=7
     * @return
     * @throws ParseException
     */
    @Override
    public String getDateOfWeeks(String beginDateStr,int djz,int zj) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(simpleDateFormat.parse(beginDateStr));
        calendar.add(Calendar.DAY_OF_MONTH,(djz-1)*7);//第几周的周一
        calendar.add(Calendar.DAY_OF_MONTH,zj-1);//第几周的周几
        return simpleDateFormat.format(calendar.getTime());
    }
      
String beginDateStr = "2022-08-21";

        try {
            String mondayDate = sxsService.getMondayDate(beginDateStr);
            int djz = 4;
            int zj = 7;
            String dateOfWeeks = sxsService.getDateOfWeeks(mondayDate, djz, zj);
            log.info("第{}周的周{}是{}:", djz, zj, dateOfWeeks);

        } catch (Exception ex) {
            log.info("{}", ex.getMessage());
        }