CalendarUtil 工具類 :時間計算,時間類型轉換

時間工具類
  • 時間類型計算
  • 時間類型轉化
/**
 * @Date: 2019/4/26 14:24
 * @Author: wangmx
 * @Description: 時間 計算工具類
 */
public class CalendarUtil {



    /**
     * @param num  爲增加的天數
     * @param newDate 初始時間
     * @return 加和日期
     */
    public static String plusDay(int num, String newDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = null;
        try {
            dt = sdf.parse(newDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.DAY_OF_YEAR, num);
        Date dt1 = rightNow.getTime();
        String reStr = sdf.format(dt1);
        return reStr;
    }

    /**
     * @param num  爲增加的天數
     * @param newDate 初始時間
     * @return 加和日期
     */
    public static Date plusDay(int num, Date newDate) {

        Date dt = newDate;
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.DAY_OF_YEAR, num);
        Date dt1 = rightNow.getTime();

        return dt1;
    }

    /**
     * @param startDate  開始時間
     * @param endDate    結束時間
     * @return 時間差值
     */
    public static int differentDays(String startDate,String endDate){

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date2 = null;
        Date date1 = null;
        try {
            date1 = format.parse(startDate);
            date2 = format.parse(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2) {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++) {
                //閏年
                if(i%4==0 && i%100!=0 || i%400==0){
                    timeDistance += 366;
                } else{    //不是閏年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        } else{    //同年
            return day2-day1;
            //return day2-day1+1;
        }
    }

    /**
     * @param startDate  開始時間
     * @param endDate    結束時間
     * @return 時間差值
     */
    public static int differentDays(Date startDate,Date endDate){

        Date date1 = startDate;
        Date date2 = endDate;
        long daysBetween=(date2.getTime()-date1.getTime())/(60*60*24*1000);
        return (int)daysBetween;
    }


    public static  String  getSimpdateFormatter(){
        long now2 = new Date().getTime();
        String a = String.valueOf(now2);
       return a;
    }


    /**
     * 判斷一個時間是否在一段時間段
     * @param
     * @param startTime
     * @param endTime
     * @return
     */
    public static boolean isEffectiveDate(int month, Date startTime, Date endTime) {
        ArrayList<Integer> result = new ArrayList<>();

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(startTime);
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(endTime);
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(curr.get(Calendar.MONTH));
            curr.add(Calendar.MONTH, 1);

        }

        if(result.contains(month)){
            return true;
        }else {
           return false;
        }
    }

    public static int kuoFeb(int month, Date startTime, Date endTime) {
        ArrayList<Integer> result = new ArrayList<>();

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(startTime);
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(endTime);
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(curr.get(Calendar.MONTH));
            curr.add(Calendar.MONTH, 1);
        }

        int j=0;
       for(int i= 0;i<result.size();i++){
          if(result.get(i)==1){
               j =j+1;
          }
       }




       return j;
    }


    /**
     *
     */
    public static BigDecimal coverMonth(String date){

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        BigDecimal zero = BigDecimal.ZERO;

        try {
            Date parse = format.parse(date);
            zero = getMonth(parse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return zero;

    }



    /**
     * 獲取兩個日期相差幾個月
     * @param start
     * @param
     * @return
     */
    public static BigDecimal getMonth(Date start) {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String format = sdf.format(start);

        Calendar min = Calendar.getInstance();
        min.setTime(start);

        int year = min.get(Calendar.YEAR);



        String time = year+"-12-31";


        int days = CalendarUtil.differentDays(format, time);

        BigDecimal days1 = BigDecimal.valueOf(days);
        BigDecimal divide = XMathUtil.divide(days1, new BigDecimal(30));

        BigDecimal bigDecimal = divide.setScale(1, BigDecimal.ROUND_HALF_UP);
        if(bigDecimal.compareTo(new BigDecimal(12)) == 1){
            bigDecimal = new BigDecimal(12);
        }
        return bigDecimal ;
    }

    /**
     * 獲取兩個日期相差幾個月
     */
    public static BigDecimal getMonth(String startTime,String endTime) {

        try {

            String format2 = "yyyy-MM-dd";
            SimpleDateFormat sdfs = new SimpleDateFormat(format2);
            Date start = sdfs.parse(startTime);
            //Date end = sdfs.parse(endTime);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            String format = sdf.format(start);

            Calendar min = Calendar.getInstance();
            min.setTime(start);

            String time = endTime;


            int days = CalendarUtil.differentDays(format, time);

            BigDecimal days1 = BigDecimal.valueOf(days);
            BigDecimal divide = XMathUtil.divide(days1, new BigDecimal(30));


            return divide.setScale(1,BigDecimal.ROUND_HALF_UP);
        }catch (Exception e){
            e.printStackTrace();
            return new BigDecimal(0);
        }
    }

    /**
     * 計算2個日期之間相差的  相差多少年 月 日
     * 比如:2011-02-02 到  2017-03-02 相差 6年,1個月,0天
     * @param fromDate
     * @param toDate
     * @return
     */
    public static int dayComparePrecise(Date fromDate, Date toDate){
        Calendar  from  =  Calendar.getInstance();
        from.setTime(fromDate);
        Calendar  to  =  Calendar.getInstance();
        to.setTime(toDate);

        int fromYear = from.get(Calendar.YEAR);
//        int fromMonth = from.get(Calendar.MONTH);
//        int fromDay = from.get(Calendar.DAY_OF_MONTH);

        int toYear = to.get(Calendar.YEAR);
//        int toMonth = to.get(Calendar.MONTH);
//        int toDay = to.get(Calendar.DAY_OF_MONTH);
        int year = toYear  -  fromYear;
//        int month = toMonth  - fromMonth;
//        int day = toDay  - fromDay;
        return year;
    }
    /**
     * 計算2個日期之間相差的  相差多少年 月 日
     * 比如:2011-02-02 到  2017-03-02 相差 6年,1個月,0天
     * @param fromDate
     * @param toDate
     * @return
     */
    public static int dayComparePreciseMonth(Date fromDate, Date toDate){
        Calendar  from  =  Calendar.getInstance();
        from.setTime(fromDate);
        Calendar  to  =  Calendar.getInstance();
        to.setTime(toDate);

        int fromMonth = from.get(Calendar.MONTH);

        int toMonth = to.get(Calendar.MONTH);
        int month = toMonth  - fromMonth;
        return month;
    }
    /**
     *兩個 時間差  2019-01-26 ,2019-02-27 ==》 1.03
     */
    public static BigDecimal getMonthDiff(String d1, String d2){
        try{

            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();

            //將String日期轉換成date

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date date1=sdf.parse(d1);
            java.util.Date date2=sdf.parse(d2);
            c1.setTime(date1);
            c2.setTime(date2);

            //判斷兩個日期的大小

            if(c2.getTimeInMillis() < c1.getTimeInMillis()) return new BigDecimal(0);
            int year1 = c1.get(Calendar.YEAR);
            int year2 = c2.get(Calendar.YEAR);
            int month1 = c1.get(Calendar.MONTH);
            int month2 = c2.get(Calendar.MONTH);
            int day1 = c1.get(Calendar.DAY_OF_MONTH);
            int day2 = c2.get(Calendar.DAY_OF_MONTH);
            // 獲取年的差值 假設 d1 = 2015-9-30   d2 = 2015-12-16
            int yearInterval = year2 - year1;
            // 如果 d1的 月-日 小於 d2的 月-日 那麼 yearInterval-- 這樣就得到了相差的年數
            if(month2 < month1 || month1 == month2 && day2 < day1) yearInterval --;
            // 獲取月數差值
            int monthInterval = (month2 + 12) - month1 ;
            if(day2 > day1) monthInterval ++;
            monthInterval %= 12;


            int  i = 0 ;
            //天數差

            if(day2 > day1) {
                i = day2 - day1;
                monthInterval = monthInterval-1;
            }
            if(day2 < day1) {
                i = day2 - day1;
                monthInterval = monthInterval-1;
            }

            i = differentDays(d1, d2);

            BigDecimal bigDecimal = new BigDecimal(i);
            BigDecimal bigDecimal2 = new BigDecimal(30);
            int DEF_DIV_SCALE =2;
            BigDecimal day = bigDecimal.divide(bigDecimal2, DEF_DIV_SCALE, BigDecimal.ROUND_HALF_UP);

            /*//月
            BigDecimal months = new BigDecimal(monthInterval);

            //年換算月份
            BigDecimal years = new BigDecimal(yearInterval);
            BigDecimal bigDecimal1 = new BigDecimal(12);
            BigDecimal yearMonth = years.multiply(bigDecimal1);

            //相加
            BigDecimal add = yearMonth.add(months);
            BigDecimal add1 = add.add(day);*/

            BigDecimal bigDecimal1 = day;

            //return add1;
            return bigDecimal1;

        }catch (Exception e){
            e.printStackTrace();
            return new BigDecimal(0);
        }

    }

    /*
     * 將時間轉換爲時間戳
     */
    public static String dateToStamp(String s) throws ParseException{
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /*
     * 將時間戳轉換爲時間
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 獲取年
     */
    public static int getYear(Date time){
        Calendar min = Calendar.getInstance();
        min.setTime(time);

        int year = min.get(Calendar.YEAR);

        return year;
    }


    /**
     * 獲取月
     */
    public static int getMonthNum(Date time){
        Calendar min = Calendar.getInstance();
        min.setTime(time);

        int month = min.get(Calendar.MONTH);
        return month;
    }

    /**
     * 獲取年
     */
    public static int getYear(String time){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse= sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar min = Calendar.getInstance();
        min.setTime(parse);

        int year = min.get(Calendar.YEAR);

        return year;
    }

    /**
     * 獲取月
     */
    public static int getMonthNum(String time){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse= sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar min = Calendar.getInstance();
        min.setTime(parse);

        int month = min.get(Calendar.MONTH);

        return month;
    }


    /**
     * Date轉換成string
     */
    public static String dateToString(Date time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(time);
        return format;
    }

    /**
     * Date轉換成string
     */
    public static String timeMillisToString(Object time){

        String countString=String.valueOf(time);
        Long count=Long.valueOf(countString);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sd = sdf.format(new Date(count));
        return sd;
    }



    /**
     * Date轉換成string
     */
    public static Date stringToDate(String time){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date=sdf.parse(time);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * Date轉換成string
     */
    public static String stringToString(String time){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date=sdf.parse(time);

            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
            String format = sdf2.format(time);

            return format;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 比較日期大小
     * <p>
     * 2017年9月7日 16:15:53
     * xj
     *
     * @param DATE1      第一個時間
     * @param DATE2      第二個時間
     * @return Integer null日期格式有誤,1:第一個日期大,0:兩個日期一樣,-1:第二個日期大
     */
    public static Date compareDate(Date DATE1, Date DATE2) {

        try {

            if (DATE1.getTime() < DATE2.getTime()) {
                return DATE1;
            } else if (DATE1.getTime() > DATE2.getTime()) {
                return DATE2;
            } else {
                return DATE1;
            }
        } catch (Exception e) {

        }

        return null;
    }

    /***
     * @comments 計算兩個時間的時間差
     * @param strTime1
     * @param strTime2
     */
    public static long getTimeDifference(String strTime1,String strTime2) {
        //格式日期格式,在此我用的是"2018-01-24 19:49:50"這種格式
        //可以更改爲自己使用的格式,例如:yyyy/MM/dd HH:mm:ss 。。。
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date now = df.parse(strTime1);
            Date date=df.parse(strTime2);
            long l=now.getTime()-date.getTime();       //獲取時間差
            long day=l/(24*60*60*1000);
            long hour=(l/(60*60*1000)-day*24);
            long min=((l/(60*1000))-day*24*60-hour*60);
            long s=(l/1000-day*24*60*60-hour*60*60-min*60);
            System.out.println(""+day+"天"+hour+"小時"+min+"分"+s+"秒");
            return day ;
        }catch(Exception e){
            e.printStackTrace();
        }
        return 0 ;
    }
    /***
     * @comments 測試使用
     * @param args
     */
    public static void main(String[] args) {
        String strTime1 = "2018-01-24";
        String strTime2 = "2018-01-23";
        long timeDifference = getTimeDifference(strTime1, strTime2);
        System.err.println(timeDifference);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章