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

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example