How to calculate days between two dates in Java 8?

In this section, we will show you how to calculate days between two dates in Java.

1. LocalDate

Main.java

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

public class Main {

public static void main(String[] args) {

LocalDate from = LocalDate.now();
LocalDate to1 = from.plusDays(10);

long result1 = ChronoUnit.DAYS.between(from, to1);
System.out.println(result1); // 10


LocalDate to2 = from.minusDays(10);

long result2 = ChronoUnit.DAYS.between(from, to2);
System.out.println(result2); // -10

}

}

Console Output:
10
-10

2. LocalDateTime

Main.java

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Main {

public static void main(String[] args) {

LocalDateTime from = LocalDateTime .now();
LocalDateTime to1 = from.plusDays(10);

long result1 = ChronoUnit.DAYS.between(from, to1);
System.out.println(result1); // 10


LocalDateTime to2 = from.minusDays(10);

long result2 = ChronoUnit.DAYS.between(from, to2);
System.out.println(result2); // -10

}

}

Console Output:
10
-10

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete