Bootstrap

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

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

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