Skip to content
Advertisement

How to calculate properly actual month count between 2 dates?

I have followed method getDiffDateMap that calculates difference between 2 dates and returns Map of Integers that represent milliseconds, seconds, minutes, hours, days, months and years respectively.

public static Map<Integer, String> getDiffDateMap(String dateA, String dateB) {

    Calendar cal = Calendar.getInstance();      
    Map<Integer,String> out = new LinkedHashMap<Integer, String>();
    long timeInMillA = 0;
    long timeInMillB = 0;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

    Date convertedDateA;
    Date convertedDateB;



    try {
        convertedDateA = dateFormat.parse(dateA);           
        cal.setTime(convertedDateA);
        timeInMillA = cal.getTimeInMillis();


        convertedDateB = dateFormat.parse(dateB);           
        cal.setTime(convertedDateB);
        timeInMillB = cal.getTimeInMillis();

    } catch (ParseException e) {
        e.printStackTrace();
    } 

    long mili = timeInMillB - timeInMillA;
    long sec = mili/1000;
    long min = sec/60;
    long hour = min/60;
    long day = hour/24;
    long week = day/7;
    long month = day/31; // ????
    long year = month/12;

    out.put(7, mili + "");
    out.put(6, sec + "");
    out.put(5, min + "");
    out.put(4, hour + "");
    out.put(3, day + "");
    out.put(2, week + "");
    out.put(1, month + "");
    out.put(0, year + "");

    return out;
}

My problem is to calculate month from actual day count:

long month = day/31; // or 30

For example:

Map<Integer,String> out = getDiffInMillsec("2012-9-01 20:9:01", "2012-10-01 20:10:01");

    System.out.println(Arrays.asList(out)); 

I get output: [{7=2592060000, 6=2592060, 5=43201, 4=720, 3=30, 2=4, 1=0, 0=0}] where 1 is month count and its 0. because difference is 30 days only. What flow need I add to fix this problem? Any suggestions?

Advertisement

Answer

I have followed method getDiffDateMap that calculates difference between 2 dates and returns Map of Integers that represent milliseconds, seconds, minutes, hours, days, months and years respectively.

Don’t reinvent the wheel 🙂

Joda Time has code to do all this and more. For example:

LocalDateTime start = ...;
LocalDateTime end = ...;
Period difference = new Period(start, end, PeriodType.yearMonthDayTime());
int months = difference.getMonths(); // etc

Note that you can’t get at the number of months when you’ve just converted the different to a number of milliseconds – as the number of months will depend on the start/end date. (30 days may or may not be a month, for example…)

I’d strongly advise you to use Joda Time throughout your Java code, in preference to java.util.*. It’s a much better API, and one which will hopefully mean you rarely-if-ever need to write your own date/time handling code.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement