Monday, March 7, 2011

Difference in two Calendar Dates

There are many ways to calculate the difference between two Calendar dates in Year, Months, weeks or days by simply dividing them with a fixed constant. DateUtil.java below has a method for getting the difference in Days. this method can similarly be modified to get in Weeks, Months or Years.

But some times the challenge is to display the difference in two java.util.Calendar  or java.util.Date in more user friendly manner. Like in format X Years, X months, X weeks, X days. Where X is positive number greater than zero.

Example: If the number of Full Years < 1, the format should be X months, X weeks, X days. If the number of Full Years >= 1 but the number of Full Months < 1, the format should be X Years, X weeks, X days and so on. Values of 0 is not written. Like "2 months, 2 days" rather than "2 months, 0 weeks, 2 days"