Difference in Days Between Two Dates in Java

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

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.

Difference in days between two dates in Java?

I would suggest you use the excellent Joda Time library instead of the flawed java.util.Date and friends. You could simply write

import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;

Date past = new Date(110, 5, 20); // June 20th, 2010
Date today = new Date(110, 6, 24); // July 24th
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays(); // => 34

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

Android calculate days between two dates

Your code for generating date object:

Date date = new Date("2/3/2017"); //deprecated

You are getting 28 days as answer because according to Date(String) constructor it is thinking day = 3,month = 2 and year = 2017

You can convert String to Date as follows:

String dateStr = "2/3/2017";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateStr);

Use above template to make your Date object. Then use below code for calculating days in between two dates. Hope this clear the thing.

It can de done as follows:

long diff = endDateValue.getTime() - startDateValue.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));

Please check link

If you use Joda Time it is much more simple:

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

Please check JodaTime

How to use JodaTime in Java Project

Calculate no of days between two dates in java

Reason is, you are not subtracting two dates with same time format.

Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.

Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();

More explaination in Jim Garrison' answer

Calculating days between two dates in JAVA (catch ParseException error)

Don't use Date. Try this.

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String date1 = "11/11/2020";
String date2 = "13/11/2020";

LocalDate d1 = LocalDate.parse(date1,dtf);
LocalDate d2 = LocalDate.parse(date2,dtf);

long ndays = d1.datesUntil(d2).count();
System.out.println(ndays);

Days between two dates. Where is the error in dates'?

Java round the result down when dividing integer numbers, so I think you have lost a day here:

System.out.println(i1/86400000);//milisec to days

After I tried Java 8 API it shows me 42900 days (note that neither Java 8 nor Excel don't include the last day in the range):

LocalDate from = LocalDate.of(1900, Month.JANUARY, 1);
LocalDate to = LocalDate.of(2017, Month.JUNE, 16);
long daysBetween = ChronoUnit.DAYS.between(from, to);

Another day was calculated by Excel in a wrong way due to a bug as described here.
So answering your question - you loose one day on rounding and another day was incorrectly added by Excel.

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


Related Topics



Leave a reply



Submit