0

I want diff of month between two dates . Diff of month calculate such as

start_date = "2017-08-30";
end_date = "2017-09-01";

diff of month is 0

and

start_date = "2017-06-05";
end_date = "2017-08-20";

diff of month is 2

and start_date = "2017-08-15"; end_date = "2017-08-15"; diff of month is 1

I am using calender of java for dates handling. After google i can not find accurate solution for that can anyone help me how can i calculate correct month diff between two dates .

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Anuj Dhiman
  • 1,550
  • 3
  • 26
  • 51
  • Convert these days in milliseconds and then perform the calculation, restore the format back by `SimpleDateFormat`class – Ashvin Sharma Sep 01 '17 at 06:41
  • please let me know more about the condition, any rounding of dates logic or simple calculate the diff of months such as diff 1.5 months? – PSo Sep 01 '17 at 06:41
  • Dublicate of [Get difference between two dates in months using Java](https://stackoverflow.com/questions/16558898/get-difference-between-two-dates-in-months-using-java) and [Java Date month difference](https://stackoverflow.com/questions/1086396/java-date-month-difference) – HAYMbl4 Sep 01 '17 at 06:43
  • Pso simple if date1 is 2017-08-30 and date2 is 2017-09-15 then month should be 0.5 – Anuj Dhiman Sep 01 '17 at 06:44

1 Answers1

4

Using java 8 you can calculate the difference between 2 Temporal objects

LocalDate start = LocalDate.of(2017, 6, 5);
LocalDate end = LocalDate.of(2017, 8, 15);
long delta = ChronoUnit.MONTHS.between(start, end);

System.out.println(delta);

ofcourse you need to create those localDate instances from the SLQ data... but that is not the big problem

using Joda (almost the same as java8 actually):

DateTime start = new DateTime().withDate(2017, 6, 5);
DateTime end = new DateTime().withDate(2017, 8, 15);

System.out.println(Months.monthsBetween(start , end).getMonths());

for the old broken java.util.Date then see the duplicated question

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97