You can use the
ChronoUnit.DAYS enum to calculate the days between two
LocalDateTime instances in Java. It provides the
between() method to calculate the amount of time between two temporal objects:
// Create date instances LocalDateTime startDateTime = LocalDateTime.parse("2022-02-12T10:40"); LocalDateTime endDateTime = LocalDateTime.parse("2022-11-12T10:40"); // Calculate the difference long days = ChronoUnit.DAYS.between(startDateTime, endDateTime); // Print days System.out.println("Days between " + startDateTime + " and " + endDateTime + ": " + days); // Days between 2022-02-12T10:40 and 2022-11-12T10:40: 273
ChronoUnit enum class was introduced in Java 8 to represent individual date and time units such as day, month, year, week, hour, minutes, etc.
between() method returns a negative number as a difference in days if the start is after the end date, as shown below:
System.out.println(ChronoUnit.DAYS.between(endDateTime, startDateTime)); // -273
You can also use the
ChronoUnit enum to calculate the difference between two
LocalDateTime objects in weeks, months, and years:
System.out.println(ChronoUnit.WEEKS.between(startDateTime, endDateTime)); // 39 System.out.println(ChronoUnit.MONTHS.between(startDateTime, endDateTime)); // 9 System.out.println(ChronoUnit.YEARS.between(startDateTime, endDateTime)); // 0
Read this article to learn more about calculating the difference between two dates in Java.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.