TOC
Java Find the difference between the number of months between two dates
In Java, twoDifference in the number of months of the dateHere is a sample program to find
The sample program supports the case where the date to be compared is a string ( yyyy/MM/dd ), java.util.
Difference in number of monthsThe following is the calculation method for determining
- First, the two dates are set to one day.
Calendar.set(Calendar.DATE, 1). - Next, the two dates are compared repeatedly on a month-by-month basis.
Add or subtract months one month at a time using Calendar.add(Calendar.MONTH, 1 or -1). - Counts the number of repeated comparisons.
sample source
execution (e.g. program)
◆Example of Execution
public static void main(String[] args) { int ret = differenceMonth("2008/6/30", "2008/6/1"); System.out.println("Result 1 = "+ret); ret = differenceMonth("2008/7/1", "2008/6/3"); System.out.println("result 2 = "+ret); ret = differenceMonth("2008/12/20", "2008/6/1"); System.out.println("result 3 = "+ret); ret = differenceMonth("2010/6/20", "2008/6/1"); System.out.println("result 4 = "+ret); ret = differenceMonth("2008/6/1", "2008/7/1"); System.out.println("result 5 = "+ret); ret = differenceMonth("2008/7/1", "2009/7/1"); System.out.println("result 6 = "+ret); ret = differenceMonth("2008/7/1", "2009/7/1"); ret = differenceMonth("2008/7/1", "2009/7/1") }
◆Execution Result
Result 1 = 0 Result 2 = 1 Result 3 = 6 Result 4 = 24 Result 5 = -1 Result 6 = -12
This sample program is a Chat&Messenger "Calendar and scheduling functionsThe actual use of the system is done in the "I'm a fan of this system.