I have start date and end date.
I need the number of months between this two dates in Java.
For example
- From date: 2009-01-29
- To date: 2009-02-02
It has one jan date and one Feb date.
It should return 2.
I have start date and end date.
I need the number of months between this two dates in Java.
For example
It has one jan date and one Feb date.
It should return 2.
You can use a Calendar or Joda time library for this.
In Joda time you can use the Days.daysBetween() method. You can then calculate the months difference. You can also use DateTime.getMonthOfYear() and do a subtraction (for dates in the same year).
using joda time would be like this (i compared how many months between today and 20/dec/2012)
Result: 41 months (from july 6th 2009)
should be easy ? :)
ps: you can also convert your date using SimpleDateFormat like:
If you don't want to use Joda (for whatever reason), you can convert your date to TimeStamp and then do the differences of milli seconds between both date and then calculate back to months. But I still prefer to use Joda time for the simplicity :)
Why not calculate with full timedate
Based on the above suggested answers I rolled my own which I added to my existing DateUtils class:
And the associatiated unit tests:
Here's a solution using
java.util.Calendar
object:As the rest say, if there's a library that will give you time differences in months, and you can use it, then you might as well.
Otherwise, if
y1
andm1
are the year and month of the first date, andy2
andm2
are the year and month of the second, then the value you want is:Note that the middle term, (m2 - m1), might be negative even though the second date is after the first one, but that's fine.
It doesn't matter whether months are taken with January=0 or January=1, and it doesn't matter whether years are AD, years since 1900, or whatever, as long as both dates are using the same basis. So for example don't mix AD and BC dates, since there wasn't a year 0 and hence BC is offset by 1 from AD.
You'd get
y1
etc. either from the dates directly if they're supplied to you in a suitable form, or using a Calendar.