Java 获取天数差(只看日期不看时间)

    /**
     * date2比date1多的天数,只看天数,不看秒数
     *
     * @param date1
     * @param date2
     * @return
     */
    private static int calDateDistance(Date date1, Date date2) {
        
        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 = Math.min(year1, year2); i < Math.max(year1, year2); i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                {
                    timeDistance += 366;
                } else    //不是闰年
                {
                    timeDistance += 365;
                }
            }
            return timeDistance + Math.abs(day2 - day1);
        } else {//同一年
            return Math.abs(day2 - day1);
        }
    }
posted @ 2022-10-25 17:06  指切  阅读(87)  评论(0编辑  收藏  举报