计算两个时间之间相差多少天

计算两个时间之间相差多少天

class DateUtil {
    // 方法1
    public static long getDiffDays1(long timestamp1, long timestamp2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTimeInMillis(timestamp1);
        cal1.set(Calendar.HOUR_OF_DAY, 0);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);

        return (timestamp2 - cal1.getTimeInMillis()) / BaseConstants.DAY_MS;
    }

    // 方法2
    public static long getDiffDays2(long timestamp1, long timestamp2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTimeInMillis(timestamp1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTimeInMillis(timestamp2);
        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;
        }
    }

    // 方法3
    public static long getDiffDays3(long timestamp1, long timestamp2) { // 0为1970-01-01 08:00:00
        long day1 = (timestamp1 + BaseConstants.HOUR_MS*8) / BaseConstants.DAY_MS;
        long day2 = (timestamp2 + BaseConstants.HOUR_MS*8) / BaseConstants.DAY_MS;
        return day2 - day1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值