Calculating Difference in Dates in Java

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

Calculate date/time difference in java

try

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

NOTE: this assumes that diff is non-negative.

How can I calculate a time difference in Java?

String time1 = "16:00:00";
String time2 = "19:00:00";

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();

Difference is in milliseconds.

I modified sfaizs post.

Calculating difference in dates in Java

I know the simple way is to take the
difference of the time in milliseconds
and then convert that into days.
However, i wanted to know if this
works in all cases (with daylight
saving, etc.).

If your times are derived from UTC dates, or they are just the difference between two calls to System.getCurrentTimeMillis() measured on the same system, you will get a valid number of milliseconds as the difference, independent of any timezone issues. (which is why everything should be using UTC as a storage format -- it's much easier to go from UTC->local time; if you try to go the other way then you need to store the local timezone along with the local time -- or attempt to infer it, gack!)

As for turning this into a number of days, you should just be able to divide by 86400000... with the caveat that there is an occasional leap second every other year or so.

How to find the duration of difference between two dates in java?

try the following

{
Date dt2 = new DateAndTime().getCurrentDateTime();

long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));

if (diffInDays > 1) {
System.err.println("Difference in number of days (2) : " + diffInDays);
return false;
} else if (diffHours > 24) {

System.err.println(">24");
return false;
} else if ((diffHours == 24) && (diffMinutes >= 1)) {
System.err.println("minutes");
return false;
}
return true;
}

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

Calculate days between two Dates in Java 8

If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);

If you want literal 24 hour days, (a duration), you can use the Duration class instead:

LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option

For more information, refer to this document.

java.util.Date Calculate difference in days

Oh yes a better solution there is!

Stop using the outmoded java.util.Date class and embrace the power of the java.time API built into Java 8 and later (tutorial). Specifically, the DateTimeFormatter, LocalDate, and ChronoUnit classes.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
LocalDate date1 = LocalDate.parse("03-29-2015", formatter);
LocalDate date2 = LocalDate.parse("03-30-2015", formatter);
long days = ChronoUnit.DAYS.between(date1, date2);
System.out.println(days); // prints 1

Java, Calculate the number of days between two dates

Note: this answer was written in 2011. I would recommend using java.time now instead of Joda Time.

Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.

I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:

int days = Days.daysBetween(date1, date2).getDays();


Related Topics



Leave a reply



Submit