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));
        }

  • 相关阅读:
    Stl源码剖析读书笔记之Alloc细节
    Lua热更系统
    Linux C++线程池
    linux sort,uniq,cut,wc.
    (转)Linux grep
    用LogParser分析IIS请求压力
    (转)MySQL主从复制的常见拓扑、原理分析以及如何提高主从复制的效率总
    AIS相关资料
    python学习笔记
    (转)MySQL InnoDB修复笔记
  • 原文地址:https://www.cnblogs.com/Jiphen/p/6180354.html
Copyright © 2011-2022 走看看