zoukankan      html  css  js  c++  java
  • java日期间相隔年月日计算

        /**
         * 获取date1相距date2多少天, date2>date1
         * @param date1
         * @param date2
         * @return
         * @throws ParseException
         */
        public static int getDaysSpace(String date1,String date2){
            Calendar cal = Calendar.getInstance();
            cal.setTime(getDate(date1, "yyyyMMdd"));
            long time1 = cal.getTimeInMillis();
            cal.setTime(getDate(date2, "yyyyMMdd"));
            long time2 = cal.getTimeInMillis();
            long between_days=(time2-time1)/(1000*3600*24);
            return Integer.parseInt(String.valueOf(between_days));
        }

        /**
         * 获取date1相距date2几个月, date2>date1
         * @param date1
         * @param date2
         * @return
         * @throws ParseException
         */
        public static float getMonthSpace(String date1, String date2){
            float result = 0;
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(getDate(date1, "yyyyMMdd"));
            c2.setTime(getDate(date2, "yyyyMMdd"));
            if(c2.get(Calendar.DATE) - c1.get(Calendar.DATE) >= 0){
                result = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12.0f + (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH)) + (c2.get(Calendar.DATE) - c1.get(Calendar.DATE))/30.0f;
            }else{
                result = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12.0f + (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH)) - 1.0f + (c2.get(Calendar.DATE) - c1.get(Calendar.DATE))/30.0f;
            }
            DecimalFormat df = new DecimalFormat("0.00");
            return Float.parseFloat(df.format(result));
        }

        /**
         * 获取date1相距date2几年, date2>date1
         * @param date1
         * @param date2
         * @return
         * @throws ParseException
         */
        public static float getYearSpace(String date1, String date2) {
            DecimalFormat df = new DecimalFormat("0.00");
            return Float.parseFloat(df.format(getMonthSpace(date1, date2)/12.0f));
        }

  • 相关阅读:
    开始我的博客园
    科技生态链
    程式建议
    如何自动识别判断url中的中文参数是GB2312还是Utf-8编码?
    jquery.cookie 使用方法
    数据结构(Java)——查找和排序(5)
    数据结构(Java)——查找和排序(4)
    数据结构(Java)——查找和排序(3)
    数据结构(Java)——查找和排序(2)
    数据结构(Java)——查找和排序(1)
  • 原文地址:https://www.cnblogs.com/Jiphen/p/6180354.html
Copyright © 2011-2022 走看看