DateTool--操作日期工具类(String和Date相互转换,获取工作日、周六、周末、节假日等)

package com.yogapay.moffice;

import org.apache.commons.lang3.StringUtils;

import static org.apache.commons.lang3.time.DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.time.DateUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

import com.qj.core.util.StringUtil;

public class DateTool{

    public static final BigDecimal NUMBER_100 = new BigDecimal(100);
    @Autowired
    private static ObjectMapper mapper=new ObjectMapper();
    
    public static long getDaySub(String beginDateStr,String endDateStr){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        long day=0;
        try {
            Date beginDate= format.parse(beginDateStr);
            Date endDate= format.parse(endDateStr);  
            day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000); 
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return day;
    }
    
    /**
     * 初始化条件查询时间:默认选中时间上月当日至本日
     * @param param
     */
    public static void initDate(Map<String,Object> param,String startDate,String endDate){
        Date end=new Date();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(end);
        calendar.add(Calendar.MONTH, -1);
        Date start = calendar.getTime();
        if(param.get(startDate)==null){
            param.put(startDate,ISO_8601_EXTENDED_DATE_FORMAT.format(start));
        }
        if(param.get(endDate)==null){
            param.put(endDate, ISO_8601_EXTENDED_DATE_FORMAT.format(end));
        }
    }
    public static Date getLastDay(Date date,int index){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, index);
        return calendar.getTime();
    }
    public static Date getLastMonth(Date date,int index){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, index);
        return calendar.getTime();
    }

    public static Date getLastYear(Date date,int index){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, index);
        return calendar.getTime();
    }
    
    public static Date getDayOfMonth(Date date,int index){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, index);
        return calendar.getTime();
    }
    public static int getMonth(Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH)+1;
    }
    public static int getDay(Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }
    
    public static int getYear(Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }
    
    public static int daysOfMonth(Date date) {
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    public static String formatTime(int time) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        hour = time / (60 * 60);
        minute = (time - 60 * 60 * hour) / 60;
        second = time - 60 * 60 * hour - 60 * minute;

        return String.format("%02d:%02d:%02d", hour, minute, second);
    }

    public static String formatLongTime(long _time) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        hour = (int) _time / (60 * 60);
        minute = (int) (_time - 60 * 60 * hour) / 60;
        second = (int) _time - (60 * 60 * hour) - minute * 60;
        return String.format("%02d:%02d:%02d", hour, minute, second);
    }

    public static Date stringToDate(String strDate,String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(strDate);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getMinusDayEndDate(Date _date) {
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(_date);
        calendar.add(Calendar.DATE, -1);
        return getStartData(calendar.getTime());
    }

    public static String dateToString(Date date, String pattern) {
        if (date == null) {
            return null;
        }

        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public static String readFileAsString(File file) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    /**
     * 获取工作日、周六、周日、节假日
     * @return 
     */
    public static LinkedHashMap<String, List<String>> getWorkWeekHoliDay(String startDate,String endDate){
        List<String> saturday=new ArrayList<>();//周六
        List<String> weekend=new ArrayList<>();//周末
        List<String> workWeekDay=new ArrayList<>();//周末周六调休
        List<String> holiday=new ArrayList<>();//节假日
        List<String> workDays=new ArrayList<>();//工作日
        
        int endMonth=Integer.valueOf(endDate.substring(5,7));
        int startMonth=Integer.valueOf(startDate.substring(5,7));
        String year=endDate.substring(0,4);
        for(int i=startMonth;i<=endMonth;i++){
            Map<String,Object> data=getHoliDayByMonth(String.format("%s-%02d",year, i),endDate);
            Object holiDays=data.get("holiDays");
            Object workWeekDays=data.get("weekDays");
            if(workWeekDays!=null){
                workWeekDay.addAll((Set<String>)workWeekDays);
            }
            if(holiDays!=null){
                holiday.addAll((Set<String>)holiDays);
            }
        }
        //获取所有周六周末,减掉调休的日期,减掉节假日可能包含周末周六
        //周六:6
        saturday=getBetweenDate(startDate, endDate, true, 6);
        if(!saturday.isEmpty()) saturday.removeAll(workWeekDay);saturday.removeAll(holiday);
        //周末:0
        weekend=getBetweenDate(startDate, endDate, true, 0);
        if(!weekend.isEmpty()) weekend.removeAll(workWeekDay);weekend.removeAll(holiday);
        //获取所有日期,减掉周六周末、节假日
        workDays=getBetweenDate(startDate, endDate, false, -1);
        workDays.removeAll(saturday);
        workDays.removeAll(weekend);
        workDays.removeAll(holiday);
        
        //
        LinkedHashMap<String,List<String>> all=new LinkedHashMap<>();
        all.put("workDays", workDays);
        all.put("saturday", saturday);
        all.put("weekend", weekend);
        all.put("holiday", holiday);
        
        return all;
    }
    
    /**
     * 获取两个日期之间的集合
     */
    public static List<String> getBetweenDate(String startTime,String endTime,boolean isWeekday,int weekType){
        // 声明保存日期集合
        List<String> list = new ArrayList<String>();
        // 转化成日期类型
        Date startDate = stringToDate(startTime, "yyyy-MM-dd");
        Date endDate = stringToDate(endTime, "yyyy-MM-dd");

        //用Calendar 进行日期比较判断
        Calendar calendar = Calendar.getInstance();
        while (startDate.getTime()<=endDate.getTime()){
            // 设置日期
            calendar.setTime(startDate);
            // 把日期添加到集合
            if(isWeekday){//计算周末周六
                int week=calendar.get(Calendar.DAY_OF_WEEK) - 1;
                if(week==weekType){//0为周日,6为周六
                    list.add(dateToString(startDate, "yyyy-MM-dd"));
                }
            }else{
                list.add(dateToString(startDate, "yyyy-MM-dd"));
            }
            //把日期增加一天
            calendar.add(Calendar.DATE, 1);
            // 获取增加后的日期
            startDate=calendar.getTime();
        }
        return list;
    }
    
    /**
     * 百度接口根据日期查询某月节假日期和周末调用日期
     * @param endDate 
     * @param month yyyy-MM
     * @return
     */
    public static Map<String, Object> getHoliDayByMonth(String month, String endDate){
        Set<String> holiDays=new HashSet<>();//节假日
        Set<String> weekDays=new HashSet<>();//周末调休日
        Date now=stringToDate(endDate, "yyyy-MM-dd");
        int nowMonth=Integer.valueOf(month.substring(5));
        String strUrl="http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query="+month+"&co=&resource_id=6018";
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(strUrl);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            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);
                sbf.append("\r\n");
            }
            Map<String,Object> result=new HashMap<>();
            result=mapper.readValue(sbf.toString(), Map.class);
            //获取全部数据
            List<Map> data=(List<Map>) result.get("data");
            //获取节假日数据
            Object holiday=data.get(0).get("holiday");
            if(holiday!=null){
                if(holiday.getClass().equals(LinkedHashMap.class)){
                    Map m=(Map) holiday;
                    forEachDate(now, nowMonth, holiDays, weekDays, m);
                }else{
                    for(Map m:(List<Map>)holiday){
                        forEachDate(now, nowMonth, holiDays, weekDays, m);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
                try {
                    if(reader!=null)reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        Map<String,Object> data=new HashMap<>();
        data.put("holiDays", holiDays);
        data.put("weekDays", weekDays);
        return data;
    }
    
    public static void forEachDate(Date now,int nowMonth,Set<String> holiDays,Set<String> weekDays,Map m){
        //获取每个节假日日期列表
        List<Map<String,Object>> list=(List<Map<String, Object>>) m.get("list");
        //遍历节假日日期
        for(Map<String,Object> m2:list){
            Date date=stringToDate(m2.get("date").toString(), "yyyy-MM-dd");
            int month2=Integer.valueOf(dateToString(date, "MM"));
            if(date.before(now)&&month2==nowMonth){//节假日小于当前日期,且为当月日期
                int status=Integer.valueOf(m2.get("status").toString());
                if(status==1){//1:放假
                    holiDays.add(dateToString(date, "yyyy-MM-dd"));
                }else{//2:周末调休
                    weekDays.add(dateToString(date, "yyyy-MM-dd"));
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值