HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Calculating months elapsed since a given date

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
elapseddatesincecalculatingmonthsgiven

Problem

I am using traceview and DDMS to analyse my operation. The following is my traceview as displayed in DDMS:

According to the above, the LoaderClass.months() function takes about 51% of the CPU time and 798.80 System time. I have reproduced this function below:

public int months(String date) {

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        try {
            d1 = f.parse(date);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        Date d2 = new Date();  
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);
        int diff = 0;
        if (c2.after(c1)) {
            while (c2.after(c1)) {
                c1.add(Calendar.MONTH, 1);
                if (c2.after(c1)) {
                    diff++;
                }
            }
        } else if (c2.before(c1)) {
            while (c2.before(c1)) {
                c1.add(Calendar.MONTH, -1);
                if (c1.before(c2)) {
                    diff--;
                }
            }
        }
        return diff;
    }


Below is a more detailed view of the method as on DDMS:

Solution

Don't reinvent the wheel for what Joda time has already written for you:

int monthsBetween = Months.monthsBetween(new LocalDate(date1), new LocalDate()).getMonths();


From the localDate doc:

  • You can pass a string in the constructor. (you could test that)



  • Empty constructor is current time.

Code Snippets

int monthsBetween = Months.monthsBetween(new LocalDate(date1), new LocalDate()).getMonths();

Context

StackExchange Code Review Q#59466, answer score: 10

Revisions (0)

No revisions yet.