3 ways to Count Number of days between two dates in java| example

In this tutorials, We are going to learn different examples about

  • Difference between two dates and return number days months and weeks

  • Given Util Date is older than 90 days

How to count the Number of days between two Localdate in java

java.time.temporal.ChronoUnit is an Enumeration class introduced in java8.

It is used to measure the time in Years, Months, Weeks, Days, Hours, Minutes. The below example finds the number of days, weeks, months, between two dates.

Here dates are [LocalDate)(/java8-ten-localdate-examples) object with no time zone information.

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class CountDays {
    public static void main(String[] args) {
        LocalDate fromDate = LocalDate.of(2021,01,05);
        LocalDate toDate = LocalDate.of(2021,02,05);
        long days = ChronoUnit.DAYS.between(fromDate, toDate);
        long weeks = ChronoUnit.WEEKS.between(fromDate, toDate);
        long months = ChronoUnit.MONTHS.between(fromDate, toDate);

        System.out.println("Days "+days);
        System.out.println("weeks "+weeks);
        System.out.println("months "+months);

    }
}

Output:

Days 31
weeks 4
months 1

How to check given date is older than 90 in java?

  • Here the date is in java.util.Date
  • First get the ZonedDateTime current time
  • using plusDays method with -90 days returns the 90days ago object.
  • Compare using isBefore method
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime 90daysAgo = now.plusDays(-90);
if (givenDate.isBefore(thirtyDaysAgo.toInstant())) {
    System.out.println("Given Date is 90 days ago")
}

Joda API to check given date is older than the current date

JODA is a library for better handling dates and times in java.

It is simple to do with this API

LocalDate fromDate = LocalDate.of(2021,01,05);
LocalDate toDate = LocalDate.of(2021,02,05);
int daysCount = Days.daysBetween(fromDate, toDate).getDays();

Conclusion

You learned to count multiple days weeks months between given dates and also check given date is older than the current date.