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 @   指切  阅读(88)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示