2

Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
how to calculate difference between two dates using java

I have try to difference two date by using some example but I have not got correct answer.

java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
 java.util.Date date1 = df.parse("2012-09-14 15:26:14+00");
 java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
 long diff = Math.abs(date2.getTime() - date1.getTime());
 System.out.println("millisecond="+diff);

I want month difference also but it didnt gave me. It is giving me difference days,hours,minute and seconds but not month.What am i doing wrong? Please help me

Edit:

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");
 long diff = Math.abs(date2.getTime() - date1.getTime());
 System.out.println(date2.getTime()+"date2");
 System.out.println(date1.getTime()+"date1");
 System.out.println("millisecond="+diff);
 diff=diff/1000;
 System.out.println("second="+diff);
 long days=diff/86400;
 days=days%86400;
 long hours=diff/3600;
 hours=hours%3600;
 long min=diff/60;
 min=min%60;
 hours=(hours-(24*days));
 String time=days+":"+hours+":"+min;
 System.out.println(time);
System.out.println("days="+days+":"+"hours="+hours+":"+"minutes"+min);

This is what i am trying to do.

Community
  • 1
  • 1
Chand Alam
  • 21
  • 1
  • 1
  • 3

5 Answers5

5

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Juvanis
  • 25,802
  • 5
  • 69
  • 87
2

call it as getDuration(date1, date2, Calendar.MONTH);

 public static long getDuration(Date returnTime, Date leaveTime, int scale) {
        long durationInMillis = returnTime.getTime() - leaveTime.getTime();
        switch (scale) {
            case Calendar.MINUTE:
                return durationInMillis / ONE_MINUTE_IN_MILLIS;
            case Calendar.MILLISECOND:
                return durationInMillis;
            case Calendar.SECOND:
                return durationInMillis / ONE_SECOND_IN_MILLIS;
            case Calendar.HOUR:
                return durationInMillis / ONE_HOUR_IN_MILLIS;
            case Calendar.DAY_OF_YEAR:
            case Calendar.DATE:
                return durationInMillis / ONE_DAY_IN_MILLIS;
            case Calendar.MONTH:
                return durationInMillis / ONE_MONTH_IN_MILLIS; // 30days per month
        }
        throw new IllegalArgumentException("invalid scale specified");
    }
Rahul
  • 15,979
  • 4
  • 42
  • 63
1

Date.getTime returns milliseconds, not seconds. You need to divide by 1000 to get seconds.

long diff = Math.abs(date2.getTime() - date1.getTime()) / 1000;

Also as mentioned in the comments your format string is incorrect. It should be this:

"yyyy-MM-dd HH:mm:ss"
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

The difference you're getting there is the number of milliseconds between the two dates, not seconds. Note that the difference between the dates you've given is not a full month.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

To start with let's change yyyy-mm-dd hh:mm:ss to yyyy-MM-dd HH:mm:ss.

The difference between dates can be calculated only with Calendar class and below is my Calendar based solution, not sure it's the best one but it is definitely doing its job. It calculates the dates difference in fill months, that is 2012-09-30 15:26:14+00 - 2012-08-30 15:26:14+00 is 1 month. But 2012-09-30 15:26:14+00 - 2012-08-30 15:26:15+00 is 0 month. Note that Locale also matters, because the result depends on light saving setting. I will not comment on it in the hopes that everything is clear from the code

public static void main(String[] args) throws Exception {
    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;
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275