0

Sorry, I tried referred the methods from Similar Method. But i still cannot get solution. How can i get the output months and days between two difference dates? Any helps would be appreciated.Thanks.

P/s : JodaTime not applicable.

What i've tried so far.

SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-yyyy");
String start       = "03-01-2015";   
String end         = "01-11-2014";

Date startdate = formatter.parse(start);
Date enddate   = formatter.parse(end);
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startdate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(enddate);

int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) -startCalendar.get(Calendar.MONTH);
Community
  • 1
  • 1
user3835327
  • 1,194
  • 1
  • 14
  • 44

2 Answers2

1

Hope this is what you want.

int diffDay= endCalendar.get(Calendar.DAY_OF_MONTH) -startCalendar.get(Calendar.DAY_OF_MONTH);

System.err.println("diffMonth==="+diffMonth +" Month(s) and " + diffDay + " Day(s)");
wam090
  • 2,823
  • 8
  • 33
  • 36
  • hi Wissam Mhaidly.. i found some error from the code.. if date from 2/8/2016 to 2/2/2017 the sql result show : 12 month -6days it supposely show 11month and 25days.. how can i fixed this hm ? – user3835327 Nov 20 '14 at 03:17
  • @user3835327 the dates above '2/8/2016 to 2/2/2017' will give you 6 months, note the dates format specified in your code above are in "dd-MM-yyyy" format not "MM-dd-yyyy" – wam090 Nov 20 '14 at 07:29
0

In java8 you can do it like this:

LocalDate startDate = LocalDate.of(2004, Month.JANUARY, 1);
LocalDate endDate = LocalDate.of(2005, Month.JANUARY, 1);

long monthsInYear2 = ChronoUnit.MONTHS.between(startDate, endDate);

(source: http://www.leveluplunch.com/java/examples/number-of-months-between-two-dates/)

Avi L
  • 1,558
  • 2
  • 15
  • 33