java时间String转换成date型及日期相差天数计算

    public static void main(String[] args) throws ParseException {
        String strTime1 = "2015-03-01 15:12:25";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd hh:MM:ss");
        Date date1 = formatter.parse(strTime1);
        String strTime2 = "2015-03-04 15:12:25";
        Date date2 = formatter.parse(strTime2);
        int dif = dateDiff(date1,date2);
        System.out.print(dif);
    }

结果:-3

其中时间的type要一致(2015-03-01 15:12:25 与 "yyyy-mm-dd hh:MM:ss"一致)

/**
     * 比较date1-date2差几天
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int dateDiff(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);
        long ldate1 = date1.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET);
        long ldate2 = date2.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET);
        // Use integer calculation, truncate the decimals
        int hr1 = (int) (ldate1 / 3600000); // 60*60*1000
        int hr2 = (int) (ldate2 / 3600000);

        int days1 = hr1 / 24;
        int days2 = hr2 / 24;

        int dateDiff = days1 - days2;
        return dateDiff;
    }

原文地址:https://www.cnblogs.com/msr1019jingzi/p/4332262.html