计算两个日期间的 天数

一、去除周末

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class IntervalDay {

    public static void main(String[] args) throws ParseException {
        int dutyDays = getDutyDays("2020-08-20","2020-08-24");
        System.out.println(dutyDays);//3天
    }

    @SuppressWarnings("deprecation")
    private static int getDutyDays(String  startDateStr, String endDateStr) throws ParseException {
        int result = 0;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = df.parse(startDateStr);
        Date endDate = df.parse(endDateStr);

        while (startDate.compareTo(endDate) <= 0) {
            if (startDate.getDay() != 6 && startDate.getDay() != 0)
                result++;
            startDate.setDate(startDate.getDate() + 1);
        }
        return result;
    }
}

  

 二、去除周末 和法定节假日(包含调休)

public static int request(String startDateStr, String endDateStr) throws ParseException {
        int result = 0;
        String temp = null;
        Integer type = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = df.parse(startDateStr);
        Date endDate = df.parse(endDateStr);
        while (startDate.compareTo(endDate) <= 0) {
            BufferedReader reader = null;
            StringBuffer sbf = new StringBuffer();
            String httpUrl="http://timor.tech/api/holiday/info/";
            httpUrl = httpUrl + df.format(startDate);
            try {
                URL url = new URL(httpUrl);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                connection.connect();
                InputStream is = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String strRead = null;
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                }
                reader.close();
                JSONParser jsonParser = new JSONParser(sbf.toString());
                 Map<String,Object> map = jsonParser.parseMap();
                 Object obj = map.get("type");
                 LinkedHashMap jsonpObject = (LinkedHashMap) obj;
                 type = Integer.parseInt(jsonpObject.get("type").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (type==0 || type ==3){
                result++;
            }
            startDate.setDate(startDate.getDate() + 1);
        }
        return result;
    }

  

posted @ 2020-08-25 10:35  叶不知秋  阅读(81)  评论(0编辑  收藏  举报