Java自动生成日历,移除节假日和周六日

Java生成日历,排除周六日以及法定节假日

一、生成简单日历,排除周六日和法定节假日
二、生成日历,农历转换,排除节假日

一、生成简单的日历
1.设置某年的开始时间和结束时间,例如:2021-01-01到2021-12-31
2.根据天获取星期几
3.排除周六日
4.手动传参排除法定节假日
5.获取到的日历写入到txt中保存

生成日历代码:

@Slf4j
public class DateWeekUtils {
   

    /**
     * 获取日期
     * @return
     */
    public static Map<String,String> getToDay(String year){
   
        Map<String,String> result = new LinkedHashMap<>();
        try {
   
        	//如果没有传入需要生成哪年的日历,则会自动生成明年的。如果传入哪年的就生成哪年的日历
            if (StringUtil.isBlank(year)){
   
                year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR) + 1);
            }
            //开始时间
            Calendar startTime = Calendar.getInstance();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            startTime.setTime(simpleDateFormat.parse(year + "-01-01"));
            //结束时间
            Calendar endTime = Calendar.getInstance();
            endTime.setTime(simpleDateFormat.parse(year + "-12-31"));
            while (startTime.compareTo(endTime) <= 0) {
   

                String week = dateToWeek(simpleDateFormat.format(startTime.getTime()));
                if (!"星期六".equals(week) && !"星期日".equals(week)){
   
                    result.put(simpleDateFormat.format(startTime.getTime()).trim(),week.trim());
                }
                //时间加一天
                startTime.set(Calendar.DATE, startTime.get(Calendar.DATE) + 1);
            }
        }catch (Exception e){
   
            log.info("DateWeekUtils-->getToDay() 获取时间错误:{}",e.getMessage());
        }
        return result;
    }

    /**
     * 根据日期获取 星期 (2019-05-06 ——> 星期一)
     * @param datetime
     * @return
     */
    private static String dateToWeek(String datetime) {
   

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {
   "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
   
            date = format.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
   
            log.info("DateWeekUtils-->dateToWeek() 获取周错误:{}",e.getMessage());
        }
        //一周的第几天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 获取当前 年月日
     * @return
     */
    public static String date(){
   
        return new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    }
}

生成的日历写入到txt中的代码:

	//日历文件存放的位置
    @Value("${vacation-file.url}")
    private String vacationPath;

    public void writeToTxt(String name, Map<String, String> dayMap, List<String> holidaySeason) {
   
        try {
   
            String line = System.getProperty("line.separator");

            StringBuffer str = new StringBuffer();

            FileWriter fw = new FileWriter(vacationPath + name + ".txt");
            //移除节假日
            if (holidaySeason != null && holidaySeason.size() > 0) {
   
                for (int i = 0; i < holidaySeason.size(); i++) {
   
                    dayMap.remove(holidaySeason.get(i));
                }
            }
            Set set = dayMap.entrySet();

            Iterator iter = set.iterator();

            while (iter.hasNext()) {
   
                Map.Entry entry = (Map.Entry) iter.next();
                str.append(entry.getKey().toString().trim() + ":" + entry.getValue().toString().trim()).append(line);
            }
            fw.write(str.toString());

            fw.close();
        } catch (Exception e) {
   
            log.info("写入到txt错误:{}", e.getMessage());
        }
    }

    public Map<String, String> readTxt(String name) {
   
        Map<String, String> map = new LinkedHashMap<>();
        try {
   
            String path = vacationPath + name + ".txt";
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)), "UTF-8"));
            String lineTxt = null;
            // 逐行读取
            while ((lineTxt = br.readLine()) != null) {
   
                // 每行数据以逗号分隔
                String[] names = lineTxt.split(":");
                // 处理数据, 可以转成entity, 在这儿转换成map
                map.put(names[0], names[1]);
            }
            br.close();
        } catch (Exception e) {
   
            log.info("读取txt失败:{}", e.getMessage());
        }
        return map;
    }
}

测试接口:

@Slf4j
@RestController
@RequestMapping("calendar")
public class CalendarController {
   

	@Autowired
    private FileUtils fileUtils;

 /**
     * 获取日历并写入到txt中
     * @param year
     * @return
     */
    @PostMapping("/toDayWeek")
    public Map<String,String> getCalendar(@RequestParam String year,@RequestParam List<String> holidaySeason){
   
        Map<String, String> toDayWeek = DateWeekUtils.getToDay(year);
        if (toDayWeek != null && toDayWeek.size() > 0) {
   
            fileUtils.writeToTxt(year, toDayWeek,holidaySeason);
        }
        return toDayWeek;
    }

    /**
     * 读取日历txt
     * @param name
     * @return
     *
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值