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 Number of days between two Localdates 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 find the number of days weeks months between two dates.

Here dates are [LocalDate)(/2018/08/java8-top-10-localdate-examples-with.html) 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:


How to check given util 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 90daysago 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 current date

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

It is an 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();
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.