Java Date Month Difference

Java 8 calculate months between two dates

Since you don't care about the days in your case. You only want the number of month between two dates, use the documentation of the period to adapt the dates, it used the days as explain by Jacob. Simply set the days of both instance to the same value (the first day of the month)

Period diff = Period.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(diff); //P3M

Same with the other solution :

long monthsBetween = ChronoUnit.MONTHS.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(monthsBetween); //3

Edit from @Olivier Grégoire comment:

Instead of using a LocalDate and set the day to the first of the month, we can use YearMonth that doesn't use the unit of days.

long monthsBetween = ChronoUnit.MONTHS.between(
YearMonth.from(LocalDate.parse("2016-08-31")),
YearMonth.from(LocalDate.parse("2016-11-30"))
)
System.out.println(monthsBetween); //3

Difference between two dates in month in java

 ZoneId defaultZoneId = ZoneId.systemDefault();
String issueDate1="01/01/2017";
Date issueDate2=new SimpleDateFormat("dd/MM/yyyy").parse(issueDate1);
String dateTo1="31/12/2018";
Date dateTo2=new SimpleDateFormat("dd/MM/yyyy").parse(dateTo1);

here year month days can find easily.This giving ans of all question.

            Instant instant = issueDate2.toInstant();
LocalDate localDatestart = instant.atZone(defaultZoneId).toLocalDate();

Instant instant1 = dateTo2.toInstant();
LocalDate localDateend = instant1.atZone(defaultZoneId).toLocalDate().plusDays(1);

Period diff = Period.between(localDatestart, localDateend);

System.out.printf("\nDifference is %d years, %d months and %d days old\n\n",
diff.getYears(), diff.getMonths(), diff.getDays());

Get difference between two dates in months using Java

If you can't use JodaTime, you can do the following:

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);

Note that if your dates are 2013-01-31 and 2013-02-01, you get a distance of 1 month this way, which may or may not be what you want.

Calculating the difference between two Java date instances

The JDK Date API is horribly broken unfortunately. I recommend using Joda Time library.

Joda Time has a concept of time Interval:

Interval interval = new Interval(oldTime, new Instant());

EDIT: By the way, Joda has two concepts: Interval for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration that represents a length of time without the actual time boundaries (e.g. represent two hours!)

If you only care about time comparisions, most Date implementations (including the JDK one) implements Comparable interface which allows you to use the Comparable.compareTo()

How to Calculate Accurate Month diff b\w two dates in java

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

Date difference in month , day

Edit: To get the months difference, you can use Calender class. Otherwise, use JodaTime library(linked at bottom of answer).

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 = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
int diffDay = endCalendar.get(Calendar.DAY_OF_MONTH) - startCalendar.get(Calendar.DAY_OF_MONTH);

Note that if your dates are 2013-01-31 and 2013-02-01, you get a distance of 1 month this way, which may or may not be what you want. To correct this, refer to this answer.

Before Edit

Just subtract the dates and calculate the milliseconds according to your needs

// Start Date : 01/14/2012 09:29:58
// End Date : 01/15/2012 10:31:48

public static void getDifference(Date d1, Date d2){

// HH converts hour in 24 hours format (0-23), day calculation
// must match with your date format
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

try {

//in milliseconds
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");

} catch (Exception e) {
e.printStackTrace();
}

}

You can also use joda-time-library and follow this tutorial's second step to implement it.



Related Topics



Leave a reply



Submit