两个日期之间的差异

时间:2013-05-16 04:15:36

标签: java date

我希望找到使用Java的2个月日期和天数之间的区别。例如: 5/16/2013 2013年7月20日之间的差异为 2个月和4天

感谢您对此事的考虑。

4 个答案:

答案 0 :(得分:7)

使用joda时间库可以更好地处理日期http://joda-time.sourceforge.net/

像这样Days.daysBetween(first DateTime, second DateTime).getDays();

答案 1 :(得分:1)

试试这个

     java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    java.util.Date date1 = df.parse("2012-09-30 15:26:14+00");
    java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
    int diff = getMonthDifference(date1, date2);
    System.out.println(diff);


    public static int getMonthDifference(java.util.Date date1, java.util.Date date2) {
        if (date1.after(date2)) {
            return getMonthDifference0(date1, date2);
        } else if (date2.after(date1)) {
            return -getMonthDifference0(date2, date1);
        }
        return 0;
    }

private static int getMonthDifference0(java.util.Date date1, java.util.Date date2) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(date1);
        c2.setTime(date2);
        int diff = 0;
        while (c2.getTimeInMillis() < c1.getTimeInMillis()) {
            c2.add(Calendar.MONTH, 1);
            diff++;
        }
        int dd = c2.get(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH);
        if (dd > 0) {
            diff--;
        } else if (dd == 0) {
            int hd = c2.get(Calendar.HOUR_OF_DAY) - c1.get(Calendar.HOUR_OF_DAY);
            if (hd > 0) {
                diff++;
            } else if (hd == 0) {
                long t1 = c1.getTimeInMillis() % (60 * 1000);
                long t2 = c2.getTimeInMillis() % (60 * 1000);
                if (t2 > t1) {
                    diff--;
                }
            }
        }
        return diff;
    }

答案 2 :(得分:1)

我会这样做

    Calendar c1 = new GregorianCalendar(2012, 0, 1);
    Calendar c2 = new GregorianCalendar(2013, 0, 2);
    int monthDiff = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
    int dayDiff;
    if (c1.get(Calendar.DATE) < c2.get(Calendar.DATE)) {
        monthDiff--;
        dayDiff = c1.getActualMaximum(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DATE) + c2.get(Calendar.DATE); 
    } else {
        dayDiff = c2.get(Calendar.DATE) - c1.get(Calendar.DATE);
    }
    System.out.println(monthDiff + " " + dayDiff);

答案 3 :(得分:0)

没有人说console.log(新日期(“2013-09-30”) - 新日期(“2012-01-01”));它会给你不同的毫秒数。在创建这两个对象时,由您决定处理时区等。