欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

统计两个日期间工作日的天数

程序员文章站 2022-05-18 08:03:52
...

 统计两个日期间工作日天数

 /**
     * 将LocalDate转成Date
     * @param localDate
     * @return
     */
    public static Date LocalDateToDate(LocalDate localDate) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
        return  Date.from(instant);
    }

    /**
     * 将Date转成LocalDate
     * @param date
     * @return
     */
    public static LocalDate dateToLocalDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        return localDateTime.toLocalDate();

    }



    /**
     * 统计两个日期间工作日天数
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return
     */
    public static Integer getWorkDays(Date startDate,Date endDate) {
        LocalDate startLocalDate = dateToLocalDate(startDate);
        LocalDate endLocalDate = dateToLocalDate(endDate);

        //List<LocalDate> holidays = Arrays.asList(LocalDate.parse("2016-01-01"), LocalDate.parse("2016-05-01"));
        // 所有节假日的日期集合(包含周末),可以参考下面获取节假日的方法
        List<String> holidays = Constant.holidays;

        // 按照起始startLocalDate,每次递增一天的方式生成一个Stream
        return Stream.iterate(startLocalDate, localDate -> localDate.plusDays(1))
                // 按照要求的时间间隔startLocalDate 至 endLocalDate中的实际间隔天数截断Stream,长度为起始时间和结束时间的差+1个
                .limit(ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1)
                // 过滤其中的节假日
                // .filter(localDate -> !holidays.contains(localDate))
                // 过滤其中的周六
                //.filter(localDate -> !DayOfWeek.SATURDAY.equals(DayOfWeek.of(localDate.get(ChronoField.DAY_OF_WEEK))))
                // 过滤其中的周日
                //.filter(localDate -> !DayOfWeek.SUNDAY.equals(DayOfWeek.of(localDate.get(ChronoField.DAY_OF_WEEK))))
                .filter(localDate -> !holidays.contains(localDate.format(fmt)))
                // 打印最后结果
                //.forEach(System.out::println);
                .collect(Collectors.toList()).size();
    }

其中,获取所有节假日API参考:http://timor.tech/api/holiday/

具体实现方法如下:

@Test
public void getHolidays() throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        String ss = restTemplate.getForObject("http://timor.tech/api/holiday/year/2020",String.class);
        JSONObject jsonObject = JSON.parseObject(ss,Feature.OrderedField);
        Object jsonObject1 =  jsonObject.get("holiday") ;
        Map<String,JSONObject> list = JSON.parseObject(JSON.toJSONString(jsonObject1),new TypeReference<LinkedHashMap<String,JSONObject>>(){}, Feature.OrderedField);
        //节假日
        List<String> allHolidays  = new ArrayList<>();
        //调休日
        List<String> restdays = new ArrayList<>();
        for(String key:list.keySet()){
            JSONObject value = list.get(key);//
            System.out.println("key:"+key+" vlaue:"+JSON.toJSONString(value));
            Boolean isHoliday = value.getBoolean("holiday");
            if (isHoliday) {
                allHolidays.add(value.getString("date"));
            } else {
                restdays.add(value.getString("date"));
            }
        }
        weekends.removeAll(restdays);
        allHolidays.addAll(weekends);
        allHolidays = allHolidays.stream().distinct().sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList());
        System.out.println(JSON.toJSONString(allHolidays));


        List<String> outList = new ArrayList<>();
        allHolidays.stream().forEach(item -> {

            StringBuilder sb = new StringBuilder("INSERT INTO workflow_holiday (`id`, `day`) VALUES (")
                    .append("'"+IdGenerator.uuid()+"'")
                    .append(",")
                    .append("'"+item+"')")
                    .append(";");
            //System.out.println(sb.toString());
            outList.add(sb.toString());


        });
        FileUtils.writeLines(getFile1("out.sql"), outList);
}


private File getFile1(String fileName) throws IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        URL url = classLoader.getResource("");

        File file = new File(url.getPath() + fileName);

        if(!file.exists()) {
            file.createNewFile();
        }
        return file;
    }

 

相关标签: Java